release: dsh-sansheng v0.1.0 (package at repo root)
This commit is contained in:
commit
7fc1fa62dc
|
|
@ -0,0 +1 @@
|
|||
node_modules/
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
# 三省六部 v0.1 内部接口契约
|
||||
|
||||
本文件约束 Web 工作台、dsh-go 原生面板与宿主服务之间的数据形状。三端共用 `src/shared/roles.js` 与 `src/shared/schema.js`。
|
||||
|
||||
## 十席
|
||||
|
||||
- `SEAT_IDS` 顺序:lead, zhongshu, shangshu, menxia, libu, hubu, lipu, bingbu, xingbu, gongbu。
|
||||
- `SEATS[id]` = `{ id, label(两字), duty(短摘要), responsibility(职责全文) }`。
|
||||
- `SEAT_GROUPS` = `{ lead:[lead], sansheng:[zhongshu,shangshu,menxia], liubu:[libu,hubu,lipu,bingbu,xingbu,gongbu] }`(工作台布局用)。
|
||||
|
||||
## 宿主 HTTP:POST `/api/sansheng`
|
||||
|
||||
请求体 `{ endpoint: string, payload?: object }`;成功回 `{ ok:true, value }`,失败回 `{ ok:false, error:{ code, message } }`(HTTP 200)。
|
||||
|
||||
| endpoint | payload | value |
|
||||
|---|---|---|
|
||||
| `list` | — | `{ projects:[{ id, name, status, revision }] }` |
|
||||
| `project` | `{ projectId }` | 项目视图(见下) |
|
||||
| `open` | `{ workspaceId, name?, path? }` | 项目视图;不存在则按 workspaceId 建项目记录(不创建会话) |
|
||||
| `enable` | `{ projectId }` | 项目视图;严格创建/恢复十席会话 |
|
||||
| `configure` | `{ projectId, seatId, model:({provider,model,reasoningEffort?}|null), instructions? }` | `{ seat }` |
|
||||
| `models` | — | `{ providers:[{ provider, models:[{ model, reasoningEffort?:[...] }] }], default:({provider,model}|null), failures:[...] }` |
|
||||
|
||||
错误码:`sansheng/invalid`、`sansheng/not-found`、`sansheng/conflict`、`sansheng/unbound`(席尚未绑定会话)、`sansheng/model-invalid`、`sansheng/state-corrupt`。
|
||||
|
||||
## 项目视图
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"revision": 0,
|
||||
"project": {
|
||||
"id": "ws-1", "name": "项目名", "workspaceId": "ws-1", "path": "D:/x", "status": "pending|provisioning|ready|error",
|
||||
"seats": [
|
||||
{ "id":"lead","label":"丞相","duty":"...","responsibility":"...","status":"pending|creating|bound|failed|missing","sessionId":null,"model":null,"instructions":"","error":null }
|
||||
],
|
||||
"groups": { "lead":["lead"], "sansheng":[...], "liubu":[...] }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 会话/模型规则(两端 UI 必须遵守)
|
||||
|
||||
- 每席一个独立 root Session;切换角色 = 导航到该席 `sessionId`,不新建、不重建聊天引擎。
|
||||
- 模型未选择显示“请选择模型”;选择后显示具体名称。界面不提供“跟随宿主模型”选项。
|
||||
- “启用”只建立十个会话,不自动运行模型。
|
||||
- 角色补充说明:Web 可编辑;原生面板只读(原生无自由文本控件)。
|
||||
|
||||
## Web 工作台(`src/client/`)
|
||||
|
||||
纯视图模型函数 `buildWorkbenchView(view, ui)` 必须可由 node 直接 import 测试(不依赖 React/DOM):
|
||||
- `view` = 项目视图;`ui` = `{ selectedSeatId, models, draft }`。
|
||||
- 返回:`{ projectTitle, ready, seats:[{id,name,duty,statusLabel,selected}], groups, selected:{ id,name,responsibility,duty,modelValue,modelLabel,instructions,modelOptions } }`。
|
||||
- `seats` 必须正好十项且 name 两字;未选模型时 `modelLabel==='请选择模型'` 且 `modelValue===''`;`modelOptions` 不得含 value==='inherit' 的项。
|
||||
React 接线用 `React.createElement`(不用 JSX,便于 esbuild 直接打包)。入口 `export const inject=[...]` + `export function apply(ctx)`。
|
||||
|
||||
## dsh-go 原生面板(`src/native/`)
|
||||
|
||||
纯视图树函数 `buildPanelView(input)` 必须可由 node 直接 import 测试:
|
||||
- `input` = `{ project, selectedSeatId, models }`。
|
||||
- 返回原生 view 节点(`{ type:'stack'|'row'|'text'|'list'|'callout'|'button'|'accordion'... }`)。
|
||||
- 硬约束:节点数 ≤120、深度 ≤8、单个 options/列表 ≤8 项、无自由文本输入控件;十席按 lead/sansheng/liubu 分组呈现。
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
# 三省六部(dsh-sansheng)· 第一版
|
||||
|
||||
在 DSH 里为每个项目提供固定的十席角色(丞相、中书、门下、尚书、吏部、户部、礼部、兵部、刑部、工部),
|
||||
每席绑定一个独立的原生命 root Session,模型与补充说明按项目独立保存。中间复用宿主原生会话,不替换聊天引擎。
|
||||
|
||||
当前进度(对应 `docs/v1-plan.md` §7 实施顺序):
|
||||
|
||||
- ✅ 第 2 步:项目内身份与十席会话绑定(宿主服务 + 严格创建/恢复/失败重试/跨项目隔离,`npm test` 用 fake ctx 验证)。
|
||||
- ✅ 第 3 步:Web 入口与右侧工作台(已在隔离测试 DSH 真机验证:入口、十席工作台、真实建十个会话、重启幂等)。
|
||||
- 🟡 第 4 步:dsh-go 原生面板(源代码就位,触摸/返回/会话跳转需真机核验)。
|
||||
- ⬜ 第 5 步:双项目联调后打包发布。
|
||||
|
||||
**本包尚未安装到任何 DSH profile,也未改动用户的日常 DSH 配置。**
|
||||
|
||||
## 目录
|
||||
|
||||
- `index.js` — 宿主插件入口(`name` / `inject` / `apply`)。
|
||||
- `src/shared/` — 十席定义与项目状态 schema(前后端共用)。
|
||||
- `src/host/` — 项目状态存储、严格会话创建/恢复、模型配置(不写 profile)、提示词 section、HTTP `api/sansheng`。
|
||||
- `src/client/` — Web 工作台(纯视图模型 + React 接线 + 传输层)。
|
||||
- `src/native/` — dsh-go 原生面板(纯视图树构造 + bridge 接线)。
|
||||
- `test/` — fake ctx 单元/集成测试。
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
# 三省六部:挂到 DSH 宿主的三省六部工作台插件。
|
||||
- insert:
|
||||
- id: sansheng
|
||||
name: 'dsh-sansheng'
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
// 三省六部宿主插件入口:只使用宿主公开注入服务,不 patch DSH,不写 profile 全局默认。
|
||||
import { SanshengStore } from './src/host/store.js'
|
||||
import { createProvisioner } from './src/host/provision.js'
|
||||
import { SanshengService } from './src/host/service.js'
|
||||
import { createApiHandler } from './src/host/api.js'
|
||||
import { installPromptSection } from './src/host/prompt.js'
|
||||
import { sanshengStatePath } from './src/host/paths.js'
|
||||
import { ROUTE } from './src/host/constants.js'
|
||||
|
||||
export const name = 'sansheng'
|
||||
export const inject = ['workspaceRegistry', 'sessionController', 'agents', 'llm', 'systemPrompt', 'connection']
|
||||
|
||||
export function apply(ctx, config = {}) {
|
||||
const store = new SanshengStore(
|
||||
typeof config.statePath === 'string' && config.statePath !== '' ? config.statePath : sanshengStatePath(config.home),
|
||||
)
|
||||
// apply 必须同步返回(cordis 把异步/非函数返回值当非法 effect);状态在首次请求时惰性读入。
|
||||
void store.ensureLoaded().catch(error => {
|
||||
console.warn(`sansheng: ${error?.message ?? error}`)
|
||||
})
|
||||
|
||||
const host = {
|
||||
workspaceRegistry: ctx.workspaceRegistry,
|
||||
sessionController: ctx.sessionController,
|
||||
agents: ctx.agents,
|
||||
llm: ctx.llm,
|
||||
}
|
||||
const provisioner = createProvisioner({ store, host })
|
||||
const service = new SanshengService({ store, host, provisioner })
|
||||
const handle = createApiHandler(service)
|
||||
|
||||
ctx.effect(() => installPromptSection(ctx, { store }), 'sansheng: prompt section')
|
||||
|
||||
// 复用宿主共享 /api 通道;浏览器带会话 Cookie 认证。
|
||||
ctx.effect(() => ctx.connection.fetch.register({
|
||||
path: ROUTE,
|
||||
methods: ['POST'],
|
||||
requestBody: 'buffered',
|
||||
fetch: async request => {
|
||||
let body
|
||||
try { body = await request.json() } catch { body = {} }
|
||||
const result = await handle(String(body?.endpoint ?? ''), body?.payload)
|
||||
return new Response(JSON.stringify(result), { status: 200, headers: { 'content-type': 'application/json' } })
|
||||
},
|
||||
}), 'sansheng: api route')
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
{
|
||||
"name": "dsh-sansheng",
|
||||
"version": "0.1.0",
|
||||
"description": "三省六部:每个项目固定十席角色与独立会话的 DSH 插件(第一版)。",
|
||||
"keywords": [
|
||||
"dsh-plugin",
|
||||
"deepseek-harness",
|
||||
"dsh",
|
||||
"sansheng",
|
||||
"multi-agent",
|
||||
"agents"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
"exports": {
|
||||
".": "./index.js",
|
||||
"./client": "./client.js",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
"client.js",
|
||||
"src/",
|
||||
"cordis.patch.yml",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "node scripts/build-client.mjs",
|
||||
"build:check": "node scripts/build-client.mjs --check",
|
||||
"test": "node --test --test-timeout=120000 \"test/*.test.js\""
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "*",
|
||||
"@deepseek-ai/dsh-llm": "*",
|
||||
"@deepseek-ai/dsh-web": "*"
|
||||
},
|
||||
"dsh": {
|
||||
"client": {
|
||||
"platform": "web",
|
||||
"inject": [
|
||||
"@deepseek-ai/dsh-client-ui-primitives"
|
||||
]
|
||||
},
|
||||
"bundle": {
|
||||
"patch": "./cordis.patch.yml"
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
"esbuild": "0.28.2"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,407 @@
|
|||
lockfileVersion: '9.0'
|
||||
|
||||
settings:
|
||||
autoInstallPeers: true
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
importers:
|
||||
|
||||
.:
|
||||
dependencies:
|
||||
'@deepseek-ai/cordis':
|
||||
specifier: '*'
|
||||
version: 4.1.0
|
||||
'@deepseek-ai/dsh-llm':
|
||||
specifier: '*'
|
||||
version: 0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-attachment@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-brand@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-brand@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-timeout@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))
|
||||
'@deepseek-ai/dsh-web':
|
||||
specifier: '*'
|
||||
version: 0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-llm@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-attachment@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-brand@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-brand@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-timeout@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0))))
|
||||
devDependencies:
|
||||
esbuild:
|
||||
specifier: 0.28.2
|
||||
version: 0.28.2
|
||||
|
||||
packages:
|
||||
|
||||
'@deepseek-ai/cordis@4.1.0':
|
||||
resolution: {integrity: sha512-CJrjNyBkKn1SfvBQUcgFYKFnLjS+uKrhdMsbHU60xabvi12d+xQ+IQSNlME5Z+B+4Zi6n4BDknKY94tEPeo47w==}
|
||||
hasBin: true
|
||||
peerDependencies:
|
||||
'@deepseek-ai/cordis-plugin-include': ~1.1.0
|
||||
'@deepseek-ai/cordis-plugin-loader': ~1.1.0
|
||||
peerDependenciesMeta:
|
||||
'@deepseek-ai/cordis-plugin-include':
|
||||
optional: true
|
||||
'@deepseek-ai/cordis-plugin-loader':
|
||||
optional: true
|
||||
|
||||
'@deepseek-ai/cosmokit@1.9.0':
|
||||
resolution: {integrity: sha512-5O1S53mZiJyZYcvxxD0Qv1EY7qFPSxbGyD8CbVK6gw7W9FvcXZj2YIX1ZkOqyQQ3Xt2rFkZDHJv0+V3Zmmp8CA==}
|
||||
|
||||
'@deepseek-ai/dsh-attachment@0.0.1-rc.1':
|
||||
resolution: {integrity: sha512-zBBw6h+YKOf7U8uEZezbFUjLsA8VU1GfCIUonAZHG2hWDWhWbrGaoO9fL8KyncEDSWMLMoIoGo+ZxDEPVJZYOA==}
|
||||
peerDependencies:
|
||||
'@deepseek-ai/cordis': ^4.0.1-rc.1
|
||||
'@deepseek-ai/dsh-brand': ^0.0.1-rc.1
|
||||
'@deepseek-ai/dsh-invariants': ^0.0.1-rc.1
|
||||
|
||||
'@deepseek-ai/dsh-brand@0.0.1-rc.1':
|
||||
resolution: {integrity: sha512-XhwNAugG/baCVA+BMMvjihYi9XMLcDUew3G63i+ATWIZCvpx8CghbgcV93DEeMH2sqhNuQAssmHgXkpRld3gyQ==}
|
||||
peerDependencies:
|
||||
'@deepseek-ai/cordis': ^4.0.1-rc.1
|
||||
'@deepseek-ai/dsh-invariants': ^0.0.1-rc.1
|
||||
|
||||
'@deepseek-ai/dsh-invariants@0.0.1-rc.1':
|
||||
resolution: {integrity: sha512-ZoGCGColviu3Tkdnv9hMkgBE4eg0hAz5GXR/knqRf7mJUeBlTCya2dIckYlqekYmp5L+1AeWxf9j+Lv1YRcvXw==}
|
||||
peerDependencies:
|
||||
'@deepseek-ai/cordis': ^4.0.1-rc.1
|
||||
|
||||
'@deepseek-ai/dsh-llm@0.0.1-rc.1':
|
||||
resolution: {integrity: sha512-mRJj07IQNfRReGrhpMpL8AONiYKqfwzxvepg/ut9Wkj8oH2BuoftPS4cMnnXFFCUlYql04/sezwDLriYks/bmw==}
|
||||
peerDependencies:
|
||||
'@deepseek-ai/cordis': ^4.0.1-rc.1
|
||||
'@deepseek-ai/dsh-attachment': ^0.0.1-rc.1
|
||||
'@deepseek-ai/dsh-brand': ^0.0.1-rc.1
|
||||
'@deepseek-ai/dsh-invariants': ^0.0.1-rc.1
|
||||
'@deepseek-ai/dsh-timeout': ^0.0.1-rc.1
|
||||
|
||||
'@deepseek-ai/dsh-timeout@0.0.1-rc.1':
|
||||
resolution: {integrity: sha512-lIMhY/JqA+eLpXXUN33xA7mlAYeHTDTWfcJ3CmEtplvGnvpDAHQ6oPeFs9JtWcfKbuNDZFMNutyhD0qoRkFQeg==}
|
||||
peerDependencies:
|
||||
'@deepseek-ai/cordis': ^4.0.1-rc.1
|
||||
'@deepseek-ai/dsh-invariants': ^0.0.1-rc.1
|
||||
|
||||
'@deepseek-ai/dsh-web@0.0.1-rc.1':
|
||||
resolution: {integrity: sha512-kbfr8aPtbsO9XOYqbdy39HwLPlVDH3GWjg9J2cJge5jgGPfN0lGlh5hcj4wvHxUEhGOZF+vieR/U8NmzeaeZMw==}
|
||||
peerDependencies:
|
||||
'@deepseek-ai/cordis': ^4.0.1-rc.1
|
||||
'@deepseek-ai/dsh-invariants': ^0.0.1-rc.1
|
||||
'@deepseek-ai/dsh-llm': ^0.0.1-rc.1
|
||||
|
||||
'@deepseek-ai/schemastery@3.19.0':
|
||||
resolution: {integrity: sha512-bDXoYQa7ghAhmdYD5VPlzKxEzJV/aKkz5l4V5h1u06z8GAPN1ROewSjvR9WiXhpa52E9fng8lpH5QdCRIQgnyQ==}
|
||||
|
||||
'@esbuild/aix-ppc64@0.28.2':
|
||||
resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [ppc64]
|
||||
os: [aix]
|
||||
|
||||
'@esbuild/android-arm64@0.28.2':
|
||||
resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [android]
|
||||
|
||||
'@esbuild/android-arm@0.28.2':
|
||||
resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm]
|
||||
os: [android]
|
||||
|
||||
'@esbuild/android-x64@0.28.2':
|
||||
resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [android]
|
||||
|
||||
'@esbuild/darwin-arm64@0.28.2':
|
||||
resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@esbuild/darwin-x64@0.28.2':
|
||||
resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@esbuild/freebsd-arm64@0.28.2':
|
||||
resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [freebsd]
|
||||
|
||||
'@esbuild/freebsd-x64@0.28.2':
|
||||
resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [freebsd]
|
||||
|
||||
'@esbuild/linux-arm64@0.28.2':
|
||||
resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-arm@0.28.2':
|
||||
resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-ia32@0.28.2':
|
||||
resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [ia32]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-loong64@0.28.2':
|
||||
resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [loong64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-mips64el@0.28.2':
|
||||
resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [mips64el]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-ppc64@0.28.2':
|
||||
resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-riscv64@0.28.2':
|
||||
resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-s390x@0.28.2':
|
||||
resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-x64@0.28.2':
|
||||
resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/netbsd-arm64@0.28.2':
|
||||
resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [netbsd]
|
||||
|
||||
'@esbuild/netbsd-x64@0.28.2':
|
||||
resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [netbsd]
|
||||
|
||||
'@esbuild/openbsd-arm64@0.28.2':
|
||||
resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [openbsd]
|
||||
|
||||
'@esbuild/openbsd-x64@0.28.2':
|
||||
resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [openbsd]
|
||||
|
||||
'@esbuild/openharmony-arm64@0.28.2':
|
||||
resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [openharmony]
|
||||
|
||||
'@esbuild/sunos-x64@0.28.2':
|
||||
resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [sunos]
|
||||
|
||||
'@esbuild/win32-arm64@0.28.2':
|
||||
resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@esbuild/win32-ia32@0.28.2':
|
||||
resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [ia32]
|
||||
os: [win32]
|
||||
|
||||
'@esbuild/win32-x64@0.28.2':
|
||||
resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@standard-schema/spec@1.1.0':
|
||||
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
|
||||
|
||||
esbuild@0.28.2:
|
||||
resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==}
|
||||
engines: {node: '>=18'}
|
||||
hasBin: true
|
||||
|
||||
snapshots:
|
||||
|
||||
'@deepseek-ai/cordis@4.1.0':
|
||||
dependencies:
|
||||
'@deepseek-ai/cosmokit': 1.9.0
|
||||
'@standard-schema/spec': 1.1.0
|
||||
|
||||
'@deepseek-ai/cosmokit@1.9.0': {}
|
||||
|
||||
'@deepseek-ai/dsh-attachment@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-brand@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0))':
|
||||
dependencies:
|
||||
'@deepseek-ai/cordis': 4.1.0
|
||||
'@deepseek-ai/dsh-brand': 0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0))
|
||||
'@deepseek-ai/dsh-invariants': 0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)
|
||||
|
||||
'@deepseek-ai/dsh-brand@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0))':
|
||||
dependencies:
|
||||
'@deepseek-ai/cordis': 4.1.0
|
||||
'@deepseek-ai/dsh-invariants': 0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)
|
||||
|
||||
'@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)':
|
||||
dependencies:
|
||||
'@deepseek-ai/cordis': 4.1.0
|
||||
'@deepseek-ai/schemastery': 3.19.0
|
||||
|
||||
'@deepseek-ai/dsh-llm@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-attachment@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-brand@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-brand@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-timeout@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))':
|
||||
dependencies:
|
||||
'@deepseek-ai/cordis': 4.1.0
|
||||
'@deepseek-ai/dsh-attachment': 0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-brand@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0))
|
||||
'@deepseek-ai/dsh-brand': 0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0))
|
||||
'@deepseek-ai/dsh-invariants': 0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)
|
||||
'@deepseek-ai/dsh-timeout': 0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0))
|
||||
'@deepseek-ai/schemastery': 3.19.0
|
||||
|
||||
'@deepseek-ai/dsh-timeout@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0))':
|
||||
dependencies:
|
||||
'@deepseek-ai/cordis': 4.1.0
|
||||
'@deepseek-ai/dsh-invariants': 0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)
|
||||
|
||||
'@deepseek-ai/dsh-web@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-llm@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-attachment@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-brand@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-brand@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-timeout@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0))))':
|
||||
dependencies:
|
||||
'@deepseek-ai/cordis': 4.1.0
|
||||
'@deepseek-ai/dsh-invariants': 0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)
|
||||
'@deepseek-ai/dsh-llm': 0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-attachment@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-brand@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-brand@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-timeout@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-invariants@0.0.1-rc.1(@deepseek-ai/cordis@4.1.0)))
|
||||
'@deepseek-ai/schemastery': 3.19.0
|
||||
|
||||
'@deepseek-ai/schemastery@3.19.0':
|
||||
dependencies:
|
||||
'@deepseek-ai/cosmokit': 1.9.0
|
||||
'@standard-schema/spec': 1.1.0
|
||||
|
||||
'@esbuild/aix-ppc64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/android-arm64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/android-arm@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/android-x64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/darwin-arm64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/darwin-x64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/freebsd-arm64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/freebsd-x64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-arm64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-arm@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-ia32@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-loong64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-mips64el@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-ppc64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-riscv64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-s390x@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-x64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/netbsd-arm64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/netbsd-x64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/openbsd-arm64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/openbsd-x64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/openharmony-arm64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/sunos-x64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/win32-arm64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/win32-ia32@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/win32-x64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@standard-schema/spec@1.1.0': {}
|
||||
|
||||
esbuild@0.28.2:
|
||||
optionalDependencies:
|
||||
'@esbuild/aix-ppc64': 0.28.2
|
||||
'@esbuild/android-arm': 0.28.2
|
||||
'@esbuild/android-arm64': 0.28.2
|
||||
'@esbuild/android-x64': 0.28.2
|
||||
'@esbuild/darwin-arm64': 0.28.2
|
||||
'@esbuild/darwin-x64': 0.28.2
|
||||
'@esbuild/freebsd-arm64': 0.28.2
|
||||
'@esbuild/freebsd-x64': 0.28.2
|
||||
'@esbuild/linux-arm': 0.28.2
|
||||
'@esbuild/linux-arm64': 0.28.2
|
||||
'@esbuild/linux-ia32': 0.28.2
|
||||
'@esbuild/linux-loong64': 0.28.2
|
||||
'@esbuild/linux-mips64el': 0.28.2
|
||||
'@esbuild/linux-ppc64': 0.28.2
|
||||
'@esbuild/linux-riscv64': 0.28.2
|
||||
'@esbuild/linux-s390x': 0.28.2
|
||||
'@esbuild/linux-x64': 0.28.2
|
||||
'@esbuild/netbsd-arm64': 0.28.2
|
||||
'@esbuild/netbsd-x64': 0.28.2
|
||||
'@esbuild/openbsd-arm64': 0.28.2
|
||||
'@esbuild/openbsd-x64': 0.28.2
|
||||
'@esbuild/openharmony-arm64': 0.28.2
|
||||
'@esbuild/sunos-x64': 0.28.2
|
||||
'@esbuild/win32-arm64': 0.28.2
|
||||
'@esbuild/win32-ia32': 0.28.2
|
||||
'@esbuild/win32-x64': 0.28.2
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
// Builds client.js (browser half) from src/client. Mirrors the DS Bot wrapper so dsh can
|
||||
// load it as a classic script and resolve platform modules from the shell.
|
||||
// node scripts/build-client.mjs writes client.js
|
||||
// node scripts/build-client.mjs --check exit 1 if client.js differs from a fresh build
|
||||
import { readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const PLUGIN = dirname(dirname(fileURLToPath(import.meta.url)))
|
||||
const OUTPUT = join(PLUGIN, 'client.js')
|
||||
const PLATFORM_MODULES = ['react', 'react-dom', '@deepseek-ai/dsh-client-ui-primitives']
|
||||
|
||||
export async function bundleClient() {
|
||||
let esbuild
|
||||
try { esbuild = await import('esbuild') } catch {
|
||||
throw new Error('缺少 esbuild:请先在包内安装 devDependencies(pnpm/npm i),再构建 client.js。')
|
||||
}
|
||||
const result = await esbuild.build({
|
||||
absWorkingDir: PLUGIN,
|
||||
entryPoints: ['src/client/index.js'],
|
||||
bundle: true,
|
||||
format: 'cjs',
|
||||
platform: 'browser',
|
||||
target: 'es2022',
|
||||
external: PLATFORM_MODULES,
|
||||
treeShaking: false,
|
||||
charset: 'utf8',
|
||||
write: false,
|
||||
logLevel: 'silent',
|
||||
})
|
||||
if (result.warnings.length > 0) throw new Error('esbuild warnings:\n' + result.warnings.map(w => w.text).join('\n'))
|
||||
return [
|
||||
'// Generated from src/client by `npm run build` (scripts/build-client.mjs). Do not edit by hand.',
|
||||
'window.__ModuleLoader__.load({',
|
||||
" id: 'dsh-sansheng',",
|
||||
' factory: (require) => {',
|
||||
'const module = { exports: {} }',
|
||||
result.outputFiles[0].text.trimEnd(),
|
||||
"return Object.defineProperty({ ...module.exports }, Symbol.toStringTag, { value: 'Module' })",
|
||||
' },',
|
||||
'})',
|
||||
'',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
const next = await bundleClient()
|
||||
if (process.argv.includes('--check')) {
|
||||
let current = ''
|
||||
try { current = readFileSync(OUTPUT, 'utf8') } catch {}
|
||||
if (current !== next) { console.error('client.js 与 src/client 不一致,请运行 npm run build'); process.exit(1) }
|
||||
console.log('client.js 是最新的')
|
||||
} else {
|
||||
writeFileSync(OUTPUT, next)
|
||||
console.log('已写出 client.js')
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,563 @@
|
|||
// 三省六部 Web 插件入口:左侧追加「三省六部」入口,点开右侧工作台。
|
||||
// 所有对宿主可选服务的调用都用 ctx.get(...) 特性探测,探测不到就降级,不伪造接口。
|
||||
|
||||
import { createElement as h, Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { SEAT_IDS, SEATS } from '../shared/roles.js'
|
||||
import {
|
||||
buildWorkbenchView,
|
||||
findModelOption,
|
||||
updateDraft,
|
||||
clearDraft,
|
||||
UNCHOSEN_MODEL_LABEL,
|
||||
} from './workbench.js'
|
||||
import { request } from './transport.js'
|
||||
import { CSS as WORKBENCH_CSS } from './styles.js'
|
||||
import { install as installNativePanel } from '../native/index.js'
|
||||
|
||||
export const inject = ['sessions', 'uiWorkspace', 'uiConversation', 'slots', 'theme', 'layout']
|
||||
|
||||
const PLUGIN_ID = 'dsh-sansheng'
|
||||
const TAB_KIND = 'sansheng-workbench'
|
||||
const TAB_TYPE_ID = 'dsh-sansheng:workbench'
|
||||
|
||||
function installStyles(doc, tag, text) {
|
||||
if (!doc || !doc.head) return null
|
||||
const style = doc.createElement('style')
|
||||
// 带上插件 id,避免被 ClientModuleSystem 当作别人的模块样式回收。
|
||||
style.dataset.plugin = PLUGIN_ID
|
||||
style.dataset.sansheng = tag
|
||||
style.textContent = text
|
||||
doc.head.appendChild(style)
|
||||
return style
|
||||
}
|
||||
|
||||
// ---------- 小图标(createElement,无 JSX) ----------
|
||||
function svgWrap(children, props) {
|
||||
return h('svg', {
|
||||
viewBox: '0 0 24 24', width: 16, height: 16, fill: 'none', stroke: 'currentColor',
|
||||
strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': 'true',
|
||||
...(props || {}),
|
||||
}, children)
|
||||
}
|
||||
const TreeIcon = (props) => svgWrap([
|
||||
h('rect', { key: 'a', x: 9, y: 2, width: 6, height: 5, rx: 1 }),
|
||||
h('path', { key: 'b', d: 'M12 7v5M5 16v-4h14v4' }),
|
||||
h('rect', { key: 'c', x: 2, y: 16, width: 6, height: 5, rx: 1 }),
|
||||
h('rect', { key: 'd', x: 16, y: 16, width: 6, height: 5, rx: 1 }),
|
||||
], props)
|
||||
const CloseIcon = (props) => svgWrap([h('path', { key: 'p', d: 'm6 6 12 12M6 18 18 6' })], props)
|
||||
const FolderIcon = (props) => svgWrap([h('path', { key: 'p', d: 'M3 7V5a2 2 0 0 1 2-2h5l2 3h7a2 2 0 0 1 2 2v11H3Z' })], props)
|
||||
const GearIcon = (props) => svgWrap([
|
||||
h('path', { key: 'a', d: 'M4 6h16M4 12h16M4 18h16' }),
|
||||
h('circle', { key: 'b', cx: 9, cy: 6, r: 2 }),
|
||||
h('circle', { key: 'c', cx: 16, cy: 12, r: 2 }),
|
||||
h('circle', { key: 'd', cx: 8, cy: 18, r: 2 }),
|
||||
], props)
|
||||
const ChevronIcon = (props) => h('svg', {
|
||||
viewBox: '0 0 24 24', width: 14, height: 14, fill: 'none', stroke: 'currentColor',
|
||||
strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round',
|
||||
className: 'ssw-chevron', 'aria-hidden': 'true',
|
||||
}, h('path', { d: 'm6 9 6 6 6-6' }))
|
||||
|
||||
function isFn(value) { return typeof value === 'function' }
|
||||
function safeCall(obj, name) {
|
||||
try {
|
||||
if (!obj || !isFn(obj[name])) return undefined
|
||||
return obj[name]()
|
||||
} catch { return undefined }
|
||||
}
|
||||
function snapshotOf(obj) {
|
||||
if (!obj) return undefined
|
||||
if (isFn(obj.getSnapshot)) {
|
||||
try { return obj.getSnapshot() } catch { return undefined }
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
export function apply(ctx) {
|
||||
if (typeof document !== 'undefined') installStyles(document, 'workbench', WORKBENCH_CSS)
|
||||
|
||||
const get = (name) => { try { return ctx.get(name) } catch { return undefined } }
|
||||
|
||||
// ---------- 当前项目 / 工作区(特性探测,拿不到就提示用户先选项目) ----------
|
||||
function workspaceItems() {
|
||||
const fromWorkspaces = snapshotOf(get('workspaces')?.list)?.items
|
||||
if (Array.isArray(fromWorkspaces)) return fromWorkspaces
|
||||
const fromUi = snapshotOf(get('uiWorkspace')?.workspaces)?.items
|
||||
if (Array.isArray(fromUi)) return fromUi
|
||||
return []
|
||||
}
|
||||
|
||||
function normalizeWorkspace(item) {
|
||||
if (!item || typeof item !== 'object') return null
|
||||
const workspaceId = item.workspaceId ?? item.id ?? null
|
||||
if (typeof workspaceId !== 'string' || !workspaceId) return null
|
||||
return {
|
||||
workspaceId,
|
||||
name: typeof item.name === 'string' ? item.name : (typeof item.title === 'string' ? item.title : undefined),
|
||||
path: typeof item.path === 'string' ? item.path : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
function currentSessionId() {
|
||||
const snap = snapshotOf(get('sessions')?.list) ?? snapshotOf(get('sessions'))
|
||||
if (!snap || typeof snap !== 'object') return null
|
||||
for (const key of ['activeId', 'currentId', 'selectedId']) {
|
||||
if (typeof snap[key] === 'string' && snap[key]) return snap[key]
|
||||
}
|
||||
if (snap.byId && typeof snap.byId === 'object') {
|
||||
const main = Object.values(snap.byId).find(session => (session?.retainedBy?.mainView ?? 0) > 0)
|
||||
if (main && typeof main.id === 'string') return main.id
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function currentWorkspaceId() {
|
||||
const candidates = []
|
||||
for (const holder of [get('workspaces'), get('uiWorkspace')]) {
|
||||
if (!holder) continue
|
||||
for (const key of ['currentWorkspaceId', 'currentId', 'activeId']) {
|
||||
if (isFn(holder[key])) candidates.push(safeCall(holder, key))
|
||||
else if (typeof holder[key] === 'string') candidates.push(holder[key])
|
||||
}
|
||||
for (const key of ['current', 'active', 'selected', 'currentWorkspace']) {
|
||||
const value = holder[key]
|
||||
const snap = snapshotOf(value)
|
||||
if (snap && typeof snap === 'object') candidates.push(snap.workspaceId ?? snap.id)
|
||||
else if (typeof value === 'string') candidates.push(value)
|
||||
}
|
||||
}
|
||||
const sessionId = currentSessionId()
|
||||
if (sessionId) {
|
||||
const owner = workspaceItems().find(item => Array.isArray(item.sessionIds) && item.sessionIds.includes(sessionId))
|
||||
if (owner) candidates.push(owner.workspaceId ?? owner.id)
|
||||
}
|
||||
return candidates.find(id => typeof id === 'string' && id) ?? null
|
||||
}
|
||||
|
||||
function currentWorkspace() {
|
||||
const items = workspaceItems().map(normalizeWorkspace).filter(Boolean)
|
||||
const id = currentWorkspaceId()
|
||||
if (id) {
|
||||
const hit = items.find(item => item.workspaceId === id)
|
||||
return hit || { workspaceId: id, name: undefined, path: undefined }
|
||||
}
|
||||
if (items.length === 1) return items[0]
|
||||
return null
|
||||
}
|
||||
|
||||
function seatRecordOf(view, id) {
|
||||
const seats = view && view.project ? view.project.seats : null
|
||||
if (Array.isArray(seats)) return seats.find(seat => seat && seat.id === id) || null
|
||||
if (seats && typeof seats === 'object') return seats[id] || null
|
||||
return null
|
||||
}
|
||||
|
||||
// ---------- 会话导航(特性探测;拿不到只发意图并 console.warn) ----------
|
||||
function navigateToSession(sessionId) {
|
||||
if (!sessionId) return false
|
||||
const attempts = []
|
||||
const ui = get('uiWorkspace')
|
||||
if (ui) {
|
||||
if (isFn(ui.openSession)) attempts.push(() => ui.openSession(sessionId))
|
||||
if (isFn(ui.open)) attempts.push(() => ui.open(sessionId))
|
||||
}
|
||||
const sessions = get('sessions')
|
||||
if (sessions) {
|
||||
if (isFn(sessions.open)) attempts.push(() => sessions.open(sessionId))
|
||||
if (isFn(sessions.openSession)) attempts.push(() => sessions.openSession(sessionId))
|
||||
if (isFn(sessions.select)) attempts.push(() => sessions.select(sessionId))
|
||||
}
|
||||
for (const name of ['navigation', 'navigator', 'router']) {
|
||||
const svc = get(name)
|
||||
if (!svc) continue
|
||||
if (isFn(svc.openSession)) attempts.push(() => svc.openSession(sessionId))
|
||||
if (isFn(svc.navigate)) attempts.push(() => svc.navigate({ sessionId }))
|
||||
if (isFn(svc.open)) attempts.push(() => svc.open(sessionId))
|
||||
}
|
||||
for (const run of attempts) {
|
||||
try {
|
||||
const result = run()
|
||||
if (result && isFn(result.then)) result.catch(() => {})
|
||||
return true
|
||||
} catch { /* 换下一个候选 */ }
|
||||
}
|
||||
console.warn('[sansheng] 未找到可用的会话导航接口,仅发出 navigate 意图:', sessionId)
|
||||
try {
|
||||
if (typeof window !== 'undefined') {
|
||||
window.dispatchEvent(new CustomEvent('sansheng:navigate', { detail: { sessionId } }))
|
||||
}
|
||||
} catch { /* 忽略 */ }
|
||||
return false
|
||||
}
|
||||
|
||||
// ---------- 右侧标签页(真实契约:register 类型 + 正文/标题 slot;不可用时回退浮动面板) ----------
|
||||
function ensureRightTab() {
|
||||
const tabs = get('sidebarRightTabs')
|
||||
return !!(tabs && isFn(tabs.get) && tabs.get(TAB_KIND))
|
||||
}
|
||||
function tryOpenRightTab() {
|
||||
const right = get('sidebarRight')
|
||||
if (!right || !isFn(right.openTab)) return false
|
||||
if (!ensureRightTab()) return false
|
||||
try { right.openTab(TAB_KIND); return true } catch (error) {
|
||||
console.warn('[sansheng] 打开右侧标签失败,改用浮动面板:', error && error.message ? error.message : error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
function SanshengTabBody() {
|
||||
return h('div', { className: 'ssw-tab-body' }, h(SanshengWorkbench, {}))
|
||||
}
|
||||
function SanshengTabTitle() {
|
||||
return h('span', { className: 'ssw-tab-title' }, '三省六部')
|
||||
}
|
||||
// 宿主按 definition.id 选 slot(TabSlot: entryKey=definition.id),因此 slot key 必须等于类型 id。
|
||||
function registerRightTabType() {
|
||||
try {
|
||||
if (!isFn(ctx.inject)) return
|
||||
ctx.inject(['sidebarRightTabs'], (injected) => {
|
||||
const tabs = injected.get('sidebarRightTabs')
|
||||
if (!tabs || !isFn(tabs.register)) return
|
||||
let disposeType = null, disposeBody = null, disposeTitle = null
|
||||
try {
|
||||
disposeType = tabs.register({ id: TAB_TYPE_ID, kind: TAB_KIND, keepMounted: true, priority: 'extension', title: () => '三省六部' })
|
||||
disposeBody = ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
|
||||
name: 'sidebar.right.pane.tab', key: TAB_TYPE_ID, inject: (sessionId) => ({ sessionId }),
|
||||
}, SanshengTabBody))
|
||||
disposeTitle = ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({
|
||||
name: 'sidebar.right.pane.tab.title', key: TAB_TYPE_ID, inject: (sessionId) => ({ sessionId }),
|
||||
}, SanshengTabTitle))
|
||||
} catch (error) {
|
||||
console.warn('[sansheng] 注册右侧标签失败:', error && error.message ? error.message : error)
|
||||
try { disposeBody && disposeBody() } catch { /* 忽略 */ }
|
||||
try { disposeTitle && disposeTitle() } catch { /* 忽略 */ }
|
||||
try { disposeType && disposeType() } catch { /* 忽略 */ }
|
||||
return
|
||||
}
|
||||
return () => {
|
||||
try { disposeBody && disposeBody() } catch { /* 忽略 */ }
|
||||
try { disposeTitle && disposeTitle() } catch { /* 忽略 */ }
|
||||
try { disposeType && disposeType() } catch { /* 忽略 */ }
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.warn('[sansheng] 注册右侧标签失败:', error && error.message ? error.message : error)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 工作台组件 ----------
|
||||
function SanshengWorkbench(props) {
|
||||
const onClose = props && props.onClose ? props.onClose : null
|
||||
const [phase, setPhase] = useState('loading')
|
||||
const [error, setError] = useState(null)
|
||||
const [notice, setNotice] = useState(null)
|
||||
const [view, setView] = useState(null)
|
||||
const [models, setModels] = useState(null)
|
||||
const [selectedSeatId, setSelectedSeatId] = useState(SEAT_IDS[0])
|
||||
const [draft, setDraft] = useState({})
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [configOpen, setConfigOpen] = useState(false)
|
||||
const [reportOpen, setReportOpen] = useState(false)
|
||||
const alive = useRef(true)
|
||||
|
||||
useEffect(() => () => { alive.current = false }, [])
|
||||
|
||||
const loadProject = useCallback(async () => {
|
||||
setPhase('loading'); setError(null); setNotice(null)
|
||||
const workspace = currentWorkspace()
|
||||
if (!workspace) { setPhase('no-workspace'); return }
|
||||
try {
|
||||
const projectView = await request('open', {
|
||||
workspaceId: workspace.workspaceId,
|
||||
name: workspace.name,
|
||||
path: workspace.path,
|
||||
})
|
||||
let modelCatalog = null
|
||||
try { modelCatalog = await request('models') } catch (modelError) {
|
||||
console.warn('[sansheng] 模型目录加载失败:', modelError && modelError.message ? modelError.message : modelError)
|
||||
}
|
||||
if (!alive.current) return
|
||||
setView(projectView)
|
||||
setModels(modelCatalog)
|
||||
setPhase('ready')
|
||||
} catch (loadError) {
|
||||
if (!alive.current) return
|
||||
setError(loadError && loadError.message ? loadError.message : '加载失败')
|
||||
setPhase('error')
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => { void loadProject() }, [loadProject])
|
||||
|
||||
const wb = buildWorkbenchView(view, { selectedSeatId, models, draft })
|
||||
const seatById = useMemo(() => {
|
||||
const map = {}
|
||||
for (const seat of wb.seats) map[seat.id] = seat
|
||||
return map
|
||||
}, [wb.seats])
|
||||
|
||||
function pickSeat(id) {
|
||||
if (!id) return
|
||||
if (id !== selectedSeatId) {
|
||||
setSelectedSeatId(id)
|
||||
setConfigOpen(false)
|
||||
}
|
||||
const seat = seatById[id]
|
||||
if (wb.ready && seat && seat.status === 'bound') {
|
||||
const rec = seatRecordOf(view, id)
|
||||
if (rec && rec.sessionId) {
|
||||
navigateToSession(rec.sessionId)
|
||||
setNotice('已切换到' + seat.name + '会话')
|
||||
return
|
||||
}
|
||||
}
|
||||
if (wb.ready && seat && seat.status !== 'bound') setNotice('该席尚未绑定会话,先启用或重试启用')
|
||||
}
|
||||
|
||||
function setModelValue(value) {
|
||||
setDraft(prev => updateDraft(prev, selectedSeatId, { modelValue: value }))
|
||||
}
|
||||
function setInstructions(value) {
|
||||
setDraft(prev => updateDraft(prev, selectedSeatId, { instructions: value }))
|
||||
}
|
||||
|
||||
async function enableSeats() {
|
||||
const projectId = view && view.project ? view.project.id : null
|
||||
if (!projectId) return
|
||||
setBusy(true); setError(null); setNotice('正在启用十席…')
|
||||
try {
|
||||
const next = await request('enable', { projectId })
|
||||
if (!alive.current) return
|
||||
setView(next)
|
||||
setNotice('十席已启用(建立独立会话,不自动运行模型)')
|
||||
} catch (enableError) {
|
||||
if (alive.current) setError(enableError && enableError.message ? enableError.message : '启用失败')
|
||||
} finally {
|
||||
if (alive.current) setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function saveConfig() {
|
||||
const projectId = view && view.project ? view.project.id : null
|
||||
if (!projectId) return
|
||||
const seatId = wb.selected.id
|
||||
const value = wb.selected.modelValue
|
||||
if (!value) { setNotice('请先为当前角色选择模型'); return }
|
||||
const option = findModelOption(wb.selected.modelOptions, value)
|
||||
const model = option
|
||||
? (option.reasoningEffort
|
||||
? { provider: option.provider, model: option.model, reasoningEffort: option.reasoningEffort }
|
||||
: { provider: option.provider, model: option.model })
|
||||
: null
|
||||
setBusy(true); setError(null); setNotice('保存中…')
|
||||
try {
|
||||
await request('configure', { projectId, seatId, model, instructions: wb.selected.instructions })
|
||||
const next = await request('project', { projectId })
|
||||
if (!alive.current) return
|
||||
setView(next)
|
||||
setDraft(prev => clearDraft(prev, seatId))
|
||||
setNotice('已保存')
|
||||
} catch (saveError) {
|
||||
if (alive.current) setError(saveError && saveError.message ? saveError.message : '保存失败')
|
||||
} finally {
|
||||
if (alive.current) setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const seatCard = (seat) => h('button', {
|
||||
key: seat.id, type: 'button', className: 'ssw-seat',
|
||||
'aria-pressed': seat.selected ? 'true' : 'false',
|
||||
title: seat.name + ' · ' + seat.duty + '(' + seat.statusLabel + ')',
|
||||
onClick: () => pickSeat(seat.id),
|
||||
},
|
||||
h('span', { className: 'ssw-role-top' },
|
||||
h('span', { className: 'ssw-role-name' }, seat.name),
|
||||
h('span', { className: 'ssw-dot', 'data-status': seat.status, 'aria-hidden': 'true' }),
|
||||
),
|
||||
h('span', { className: 'ssw-role-duty' }, seat.duty),
|
||||
)
|
||||
|
||||
const pickList = (ids) => ids.map(id => seatById[id]).filter(Boolean)
|
||||
const tree = h('section', { className: 'ssw-tree', 'aria-label': '切换角色' },
|
||||
h('div', { className: 'ssw-lead' }, pickList(wb.groups.lead).map(seatCard)),
|
||||
h('div', { className: 'ssw-sansheng' },
|
||||
h('span', { className: 'ssw-group-label' }, '三省'),
|
||||
h('div', { className: 'ssw-trio' }, pickList(wb.groups.sansheng).map(seatCard)),
|
||||
),
|
||||
h('div', { className: 'ssw-ministries' },
|
||||
h('span', { className: 'ssw-group-label' }, '六部 · 尚书统筹'),
|
||||
h('div', { className: 'ssw-six' }, pickList(wb.groups.liubu).map(seatCard)),
|
||||
),
|
||||
)
|
||||
|
||||
const head = h('header', { className: 'ssw-head' },
|
||||
h(TreeIcon),
|
||||
h('strong', { className: 'ssw-head-title' }, '工作台'),
|
||||
onClose
|
||||
? h('button', { type: 'button', className: 'ssw-icon-btn', onClick: onClose, 'aria-label': '收起工作台' }, h(CloseIcon))
|
||||
: null,
|
||||
)
|
||||
|
||||
const projectInfo = h('div', { className: 'ssw-project' },
|
||||
h('div', { className: 'ssw-project-line' },
|
||||
h('span', { className: 'ssw-eyebrow' }, h(FolderIcon), '当前项目'),
|
||||
h('span', { className: 'ssw-count' }, wb.project.seatCount + ' 个角色 · ' + wb.project.sessionCount + ' 个会话'),
|
||||
),
|
||||
h('div', { className: 'ssw-project-title' }, wb.projectTitle || '未命名项目'),
|
||||
)
|
||||
|
||||
const enableBlock = !wb.ready
|
||||
? h('div', { className: 'ssw-enable' },
|
||||
h('p', { className: 'ssw-enable-note' }, '这个项目还没有启用十席。启用会建立十个独立会话,但不会自动运行模型。'),
|
||||
h('button', {
|
||||
type: 'button', className: 'ssw-primary', disabled: busy, onClick: enableSeats,
|
||||
}, busy ? '正在启用…' : '启用此项目的十席'),
|
||||
)
|
||||
: null
|
||||
|
||||
const currentCard = h('section', { className: 'ssw-current' },
|
||||
h('div', { className: 'ssw-current-top' },
|
||||
h('strong', { className: 'ssw-current-name' }, wb.selected.name),
|
||||
h('span', { className: 'ssw-current-label' }, '角色职责 · ' + wb.selected.statusLabel),
|
||||
),
|
||||
h('p', { className: 'ssw-current-text' }, wb.selected.responsibility),
|
||||
)
|
||||
|
||||
const optionEls = wb.selected.modelOptions.map(option => h('option', { key: option.value, value: option.value }, option.label))
|
||||
if (wb.selected.modelValue && !wb.selected.modelOptions.some(option => option.value === wb.selected.modelValue)) {
|
||||
optionEls.push(h('option', { key: '__current__', value: wb.selected.modelValue }, wb.selected.modelLabel))
|
||||
}
|
||||
const config = h('section', { className: 'ssw-config' },
|
||||
h('button', {
|
||||
type: 'button', className: 'ssw-config-toggle', 'aria-expanded': configOpen ? 'true' : 'false',
|
||||
onClick: () => setConfigOpen(value => !value),
|
||||
},
|
||||
h(GearIcon),
|
||||
h('span', null, '配置' + wb.selected.name + (wb.selected.dirty ? ' · 未保存' : '')),
|
||||
h(ChevronIcon),
|
||||
),
|
||||
configOpen
|
||||
? h('div', { className: 'ssw-config-body' },
|
||||
h('label', { className: 'ssw-label' }, '会话模型'),
|
||||
h('select', {
|
||||
className: 'ssw-field', value: wb.selected.modelValue, disabled: busy,
|
||||
onChange: event => setModelValue(event.target.value),
|
||||
},
|
||||
h('option', { value: '', disabled: true }, UNCHOSEN_MODEL_LABEL),
|
||||
...optionEls,
|
||||
),
|
||||
h('label', { className: 'ssw-label' }, '角色补充说明'),
|
||||
h('textarea', {
|
||||
className: 'ssw-field ssw-textarea', rows: 4, value: wb.selected.instructions, disabled: busy,
|
||||
placeholder: '补充该角色在当前项目中的工作要求',
|
||||
onChange: event => setInstructions(event.target.value),
|
||||
}),
|
||||
h('p', { className: 'ssw-scope-note' }, '每个角色是独立会话;模型与说明只影响当前项目当前角色,不改变宿主默认模型。'),
|
||||
h('div', { className: 'ssw-save-row' },
|
||||
h('button', { type: 'button', className: 'ssw-primary', disabled: busy, onClick: saveConfig }, busy ? '保存中…' : '保存配置'),
|
||||
wb.selected.dirty ? h('span', { className: 'ssw-save-status' }, '有未保存修改') : null,
|
||||
),
|
||||
)
|
||||
: null,
|
||||
)
|
||||
|
||||
const report = h('section', { className: 'ssw-report' },
|
||||
h('button', {
|
||||
type: 'button', className: 'ssw-report-toggle', 'aria-expanded': reportOpen ? 'true' : 'false',
|
||||
onClick: () => setReportOpen(value => !value),
|
||||
}, reportOpen ? '收起职责汇报' : '全部汇报职责'),
|
||||
reportOpen
|
||||
? h('div', { className: 'ssw-report-list' },
|
||||
SEAT_IDS.map(id => {
|
||||
const rec = seatRecordOf(view, id)
|
||||
const m = rec && rec.model
|
||||
const modelLabel = m && m.model ? (m.model + (m.reasoningEffort ? ' · ' + m.reasoningEffort : '')) : '未选择模型'
|
||||
return h('div', { key: id, className: 'ssw-report-item', 'data-seat': id },
|
||||
h('div', { className: 'ssw-report-head' },
|
||||
h('strong', null, SEATS[id].label),
|
||||
h('span', null, SEATS[id].duty),
|
||||
),
|
||||
h('p', { className: 'ssw-report-model' }, '模型:' + modelLabel),
|
||||
h('p', { className: 'ssw-report-text' }, SEATS[id].responsibility),
|
||||
)
|
||||
}),
|
||||
)
|
||||
: null,
|
||||
)
|
||||
|
||||
const statusEl = error
|
||||
? h('p', { className: 'ssw-error', role: 'alert' }, error)
|
||||
: (notice ? h('p', { className: 'ssw-notice', role: 'status' }, notice) : null)
|
||||
|
||||
let body
|
||||
if (phase === 'loading') body = h('div', { className: 'ssw-loading' }, '正在加载工作台…')
|
||||
else if (phase === 'no-workspace') body = h('div', { className: 'ssw-empty' },
|
||||
h('p', null, '先从左侧选择一个项目'),
|
||||
h('button', { type: 'button', className: 'ssw-primary', onClick: loadProject }, '重试'),
|
||||
)
|
||||
else if (phase === 'error' && !view) body = h('div', { className: 'ssw-empty' },
|
||||
h('p', { className: 'ssw-error' }, error || '加载失败'),
|
||||
h('button', { type: 'button', className: 'ssw-primary', onClick: loadProject }, '重试'),
|
||||
)
|
||||
else body = h(Fragment, null, projectInfo, enableBlock, tree, report, currentCard, config, statusEl)
|
||||
|
||||
return h('div', { className: 'ssw-root ssw-scope' }, head, body)
|
||||
}
|
||||
|
||||
// ---------- 左侧入口 ----------
|
||||
function SanshengEntry(props) {
|
||||
const compact = !!(props && props.compact)
|
||||
const [floating, setFloating] = useState(false)
|
||||
const onClick = () => {
|
||||
if (tryOpenRightTab()) { setFloating(false); return }
|
||||
setFloating(value => !value)
|
||||
}
|
||||
let panel = null
|
||||
if (floating) {
|
||||
const card = h('div', { className: 'ssw-float', role: 'dialog', 'aria-label': '三省六部工作台' },
|
||||
h(SanshengWorkbench, { onClose: () => setFloating(false) }))
|
||||
const canPortal = typeof document !== 'undefined' && document.body && isFn(createPortal)
|
||||
panel = canPortal ? createPortal(card, document.body) : card
|
||||
}
|
||||
return h(Fragment, null,
|
||||
h('button', {
|
||||
type: 'button', className: compact ? 'ssw-entry ssw-entry-compact' : 'ssw-entry', title: '三省六部',
|
||||
'aria-expanded': floating ? 'true' : 'false', onClick,
|
||||
},
|
||||
h(TreeIcon),
|
||||
h('span', { className: 'ssw-entry-label' }, '三省六部'),
|
||||
),
|
||||
panel,
|
||||
)
|
||||
}
|
||||
|
||||
function SanshengSessionAction(props) {
|
||||
const children = props && props.children
|
||||
return h(Fragment, null, children, h(SanshengEntry, { compact: true }))
|
||||
}
|
||||
|
||||
// 顶部入口:包住「新会话」行(HOC 槽位),在原按钮后追加「三省六部」,不替换原按钮/项目树。
|
||||
try {
|
||||
if (ctx.slots && isFn(ctx.slots.inject) && isFn(ctx.slots.register)) {
|
||||
ctx.slots.inject('sidebar.session.action', () => ctx.slots.register({
|
||||
name: 'sidebar.session.action',
|
||||
id: 'sansheng-entry',
|
||||
}, SanshengSessionAction))
|
||||
} else {
|
||||
console.warn('[sansheng] 宿主未提供 slots.inject / slots.register,无法注册侧栏入口')
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[sansheng] 注册侧栏入口失败:', error && error.message ? error.message : error)
|
||||
}
|
||||
|
||||
// 右侧工作台标签类型:需在 apply 时就注册(宿主按类型 id 选正文 slot)。
|
||||
registerRightTabType()
|
||||
|
||||
// dsh-go 原生面板:浏览器(无 dshGo 服务)或桥未就绪时,install 内部安静退出。
|
||||
try {
|
||||
installNativePanel(ctx)
|
||||
} catch (error) {
|
||||
console.warn('[sansheng] 原生面板注册失败:', error && error.message ? error.message : error)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
// 三省六部工作台样式:白蓝主题,自带深色适配。
|
||||
// 所有选择器以 .ssw- 前缀隔离,避免污染宿主样式;变量参考 preview/index.html。
|
||||
// 不依赖任何构建工具,作为普通字符串导出,由入口注入 <style>。
|
||||
|
||||
export const CSS = `
|
||||
.ssw-scope{--ssw-bg:#ffffff;--ssw-side:#f8f9fa;--ssw-rail:#f7f9fc;--ssw-card:#ffffff;--ssw-line:#e3e8ef;--ssw-strong:#c7d8f5;--ssw-ink:#0f172a;--ssw-muted:#667085;--ssw-faint:#98a2b3;--ssw-blue:#3b82f6;--ssw-wash:#eff6ff;--ssw-frame:#3b82f6;--ssw-wire:#c9d6ea;--ssw-danger:#dc2626;--ssw-ok:#16a34a;box-sizing:border-box;color:var(--ssw-ink);font-family:Inter,"Segoe UI","Microsoft YaHei",sans-serif;font-size:13px;line-height:1.5}
|
||||
.ssw-scope *,.ssw-scope *::before,.ssw-scope *::after{box-sizing:border-box}
|
||||
.ssw-scope button{font:inherit;color:inherit;background:transparent;border:0;cursor:pointer}
|
||||
.ssw-scope button:disabled{cursor:default;opacity:.55}
|
||||
.ssw-scope :focus-visible{outline:2px solid var(--ssw-blue);outline-offset:2px}
|
||||
body[data-ds-dark-theme] .ssw-scope,html[data-theme=dark] .ssw-scope,.ssw-scope[data-ssw-theme=dark]{--ssw-bg:#14171c;--ssw-side:#171b21;--ssw-rail:#161a20;--ssw-card:#1e232b;--ssw-line:#2c333d;--ssw-strong:#3b4a63;--ssw-frame:#6ea8ff;--ssw-ink:#e6ebf2;--ssw-muted:#a9b4c2;--ssw-faint:#7b8797;--ssw-blue:#6ea8ff;--ssw-wash:#1d2b40;--ssw-wire:#3a4350;--ssw-danger:#f87171;--ssw-ok:#4ade80}
|
||||
.ssw-float{position:fixed;right:14px;bottom:70px;z-index:2147483000;width:min(374px,calc(100vw - 28px));max-height:calc(100vh - 96px);display:flex;flex-direction:column;background:#ffffff;border:1px solid #e3e8ef;border-radius:12px;box-shadow:0 18px 50px -12px rgba(16,24,40,.28),0 4px 12px -2px rgba(16,24,40,.12);overflow:hidden}
|
||||
body[data-ds-dark-theme] .ssw-float,html[data-theme=dark] .ssw-float{background:#161a20;border-color:#2c333d}
|
||||
.ssw-root{display:flex;flex-direction:column;min-height:0;height:100%;overflow:auto;background:var(--ssw-rail);color:var(--ssw-ink)}
|
||||
.ssw-head{flex:none;height:52px;display:flex;align-items:center;gap:8px;padding:0 16px;border-bottom:1px solid var(--ssw-line);background:var(--ssw-card)}
|
||||
.ssw-head svg{width:18px;height:18px;color:var(--ssw-muted)}
|
||||
.ssw-head-title{font-size:13px;font-weight:600}
|
||||
.ssw-icon-btn{margin-left:auto;display:inline-flex;align-items:center;justify-content:center;width:30px;height:30px;border-radius:6px;color:var(--ssw-muted)}
|
||||
.ssw-icon-btn:hover{background:var(--ssw-wash);color:var(--ssw-blue)}
|
||||
.ssw-project{padding:18px 16px 0}
|
||||
.ssw-project-line{display:flex;align-items:center;justify-content:space-between;margin-bottom:5px}
|
||||
.ssw-eyebrow{display:inline-flex;align-items:center;gap:6px;font-size:11px;color:var(--ssw-muted)}
|
||||
.ssw-eyebrow svg{width:14px;height:14px}
|
||||
.ssw-count{font-size:10px;color:var(--ssw-faint)}
|
||||
.ssw-project-title{font-size:17px;font-weight:600;letter-spacing:.3px;margin:0 0 14px}
|
||||
.ssw-enable{margin:0 16px 4px;padding:12px;border:1px solid var(--ssw-strong);background:var(--ssw-wash);border-radius:10px}
|
||||
.ssw-enable-note{margin:0 0 10px;font-size:12px;color:var(--ssw-muted);line-height:1.7}
|
||||
.ssw-primary{background:var(--ssw-blue);color:#ffffff;border-radius:7px;padding:8px 13px;font-size:12px;font-weight:500}
|
||||
.ssw-primary:hover{filter:brightness(1.05)}
|
||||
.ssw-tree{padding:14px 16px 4px;position:relative}
|
||||
.ssw-lead{width:150px;margin:0 auto;position:relative}
|
||||
.ssw-lead::after{content:none}
|
||||
.ssw-sansheng{position:relative;margin-top:22px}
|
||||
.ssw-trio{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:9px}
|
||||
.ssw-seat{position:relative;width:100%;display:flex;flex-direction:column;gap:6px;padding:10px 9px 8px;border:1.5px solid var(--ssw-frame);border-radius:10px;background:var(--ssw-card);text-align:left;min-height:70px;box-shadow:0 1px 2px rgba(16,24,40,.04);transition:border-color .15s,box-shadow .15s,transform .15s}
|
||||
.ssw-seat:hover{border-color:var(--ssw-blue);transform:translateY(-1px);box-shadow:0 3px 8px rgba(16,24,40,.06)}
|
||||
.ssw-seat[aria-pressed=true]{border-color:var(--ssw-blue);background:var(--ssw-wash);box-shadow:0 0 0 2px rgba(59,130,246,.12)}
|
||||
.ssw-lead .ssw-seat{border-color:var(--ssw-blue)}
|
||||
.ssw-role-top{display:flex;align-items:center;justify-content:space-between;gap:6px}
|
||||
.ssw-role-name{font-size:14px;font-weight:600;letter-spacing:2px}
|
||||
.ssw-role-duty{font-size:10px;color:var(--ssw-muted);line-height:1.5}
|
||||
.ssw-dot{flex:none;width:6px;height:6px;border-radius:50%;border:1px solid var(--ssw-faint);background:transparent}
|
||||
.ssw-dot[data-status=bound]{background:var(--ssw-ok);border-color:var(--ssw-ok)}
|
||||
.ssw-dot[data-status=failed],.ssw-dot[data-status=missing]{background:var(--ssw-danger);border-color:var(--ssw-danger)}
|
||||
.ssw-dot[data-status=creating]{background:var(--ssw-blue);border-color:var(--ssw-blue)}
|
||||
.ssw-ministries{position:relative;margin-top:18px}
|
||||
.ssw-group-label{display:block;margin:0 2px 8px;font-size:11px;font-weight:600;letter-spacing:.5px;color:var(--ssw-muted)}
|
||||
.ssw-six{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}
|
||||
.ssw-six .ssw-seat{min-height:66px;padding:9px 8px}
|
||||
.ssw-report{padding:0 16px;margin-top:4px}
|
||||
.ssw-report-toggle{font-size:12px;color:var(--ssw-blue);padding:7px 2px;font-weight:500}
|
||||
.ssw-report-list{display:flex;flex-direction:column;gap:8px;margin-top:4px}
|
||||
.ssw-report-item{border:1px solid var(--ssw-line);border-radius:9px;padding:9px 11px;background:var(--ssw-card)}
|
||||
.ssw-report-head{display:flex;gap:8px;align-items:baseline}
|
||||
.ssw-report-head strong{font-size:13px;letter-spacing:1px}
|
||||
.ssw-report-head span{font-size:10px;color:var(--ssw-muted)}
|
||||
.ssw-report-model{margin:4px 0 0;font-size:11px;color:var(--ssw-blue);letter-spacing:.2px}
|
||||
.ssw-report-text{margin:4px 0 0;font-size:12px;line-height:1.7;color:var(--ssw-muted)}
|
||||
.ssw-current{margin:16px 16px 0;padding:13px;border:1px solid var(--ssw-line);border-radius:11px;background:var(--ssw-card)}
|
||||
.ssw-current-top{display:flex;align-items:center;justify-content:space-between;margin-bottom:9px}
|
||||
.ssw-current-name{font-size:13px;font-weight:600}
|
||||
.ssw-current-label{font-size:10px;color:var(--ssw-faint)}
|
||||
.ssw-current-text{margin:0;font-size:12px;line-height:1.8;color:var(--ssw-muted)}
|
||||
.ssw-config{margin:10px 16px 0;border:1px solid var(--ssw-line);border-radius:10px;background:var(--ssw-card);overflow:hidden}
|
||||
.ssw-config-toggle{display:flex;align-items:center;gap:8px;width:100%;padding:12px 13px;font-size:12px;color:var(--ssw-ink)}
|
||||
.ssw-config-toggle svg{width:15px;height:15px;color:var(--ssw-muted)}
|
||||
.ssw-chevron{margin-left:auto;transition:transform .2s}
|
||||
.ssw-config-toggle[aria-expanded=true] .ssw-chevron{transform:rotate(180deg)}
|
||||
.ssw-config-body{padding:0 13px 14px}
|
||||
.ssw-label{display:block;font-size:11px;color:var(--ssw-muted);margin:12px 0 6px}
|
||||
.ssw-field{width:100%;border:1px solid var(--ssw-line);background:var(--ssw-bg);color:var(--ssw-ink);border-radius:6px;padding:8px;font-size:12px;line-height:1.5}
|
||||
.ssw-textarea{resize:vertical;min-height:84px;font-family:inherit}
|
||||
.ssw-scope-note{margin:10px 0;font-size:10px;line-height:1.6;color:var(--ssw-faint)}
|
||||
.ssw-save-row{display:flex;align-items:center;gap:10px}
|
||||
.ssw-save-status{font-size:10px;color:var(--ssw-muted)}
|
||||
.ssw-notice{margin:12px 16px 16px;font-size:11px;color:var(--ssw-muted)}
|
||||
.ssw-error{margin:12px 16px 16px;font-size:11px;color:var(--ssw-danger)}
|
||||
.ssw-loading,.ssw-empty{padding:36px 20px;text-align:center;font-size:12px;color:var(--ssw-muted)}
|
||||
.ssw-empty .ssw-primary{margin-top:12px}
|
||||
.ssw-entry{display:flex;align-items:center;gap:9px;width:100%;padding:0 10px;height:35px;border-radius:7px;font-size:13px;color:inherit;text-align:left}
|
||||
.ssw-entry:hover{background:#eef4ff}
|
||||
.ssw-entry[aria-expanded=true]{color:#2563eb;background:#eaf1fe;font-weight:600}
|
||||
.ssw-entry svg{width:16px;height:16px;flex:none}
|
||||
.ssw-entry-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.ssw-entry-compact{width:auto;max-width:100%;height:28px;padding:0 8px;gap:6px;border:1px solid var(--ssw-line);border-radius:7px;background:var(--ssw-card);font-size:12px}
|
||||
.ssw-entry-compact:hover{background:var(--ssw-wash)}
|
||||
body[data-ds-dark-theme] .ssw-entry:hover{background:#1d2b40}
|
||||
body[data-ds-dark-theme] .ssw-entry[aria-expanded=true]{color:#91bafa;background:#1d2b40}
|
||||
@media (prefers-reduced-motion:reduce){.ssw-scope *{transition:none!important}}
|
||||
.ssw-tab-body{height:100%;min-height:0;display:flex;flex-direction:column}
|
||||
.ssw-tab-body .ssw-root{flex:1;min-height:0}
|
||||
.ssw-tab-title{font-size:13px}
|
||||
`
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
// 三省六部 Web 传输层:POST api/sansheng,契约见 CONTRACT.md。
|
||||
// 请求体 { endpoint, payload };成功 { ok:true, value };失败 { ok:false, error:{code,message} }。
|
||||
|
||||
const ROUTE = 'api/sansheng'
|
||||
|
||||
export class SanshengRequestError extends Error {
|
||||
constructor(message, code) {
|
||||
super(message)
|
||||
this.name = 'SanshengRequestError'
|
||||
this.code = code || 'sansheng/error'
|
||||
}
|
||||
}
|
||||
|
||||
export async function request(endpoint, payload, signal) {
|
||||
let response
|
||||
try {
|
||||
response = await fetch(ROUTE, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ endpoint, payload: payload ?? null }),
|
||||
signal,
|
||||
})
|
||||
} catch (error) {
|
||||
if (error && error.name === 'AbortError') throw error
|
||||
const detail = error && error.message ? error.message : String(error)
|
||||
throw new SanshengRequestError('无法连接 DSH,请确认它仍在运行(' + detail + ')', 'NETWORK')
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new SanshengRequestError('HTTP ' + response.status, 'HTTP_' + response.status)
|
||||
}
|
||||
|
||||
let result
|
||||
try {
|
||||
result = await response.json()
|
||||
} catch (error) {
|
||||
throw new SanshengRequestError('响应不是合法 JSON', 'sansheng/bad-response')
|
||||
}
|
||||
|
||||
if (!result || result.ok !== true) {
|
||||
const code = result && result.error && result.error.code ? result.error.code : 'sansheng/error'
|
||||
const message = result && result.error && result.error.message ? result.error.message : '请求失败'
|
||||
throw new SanshengRequestError(message, code)
|
||||
}
|
||||
return result.value
|
||||
}
|
||||
|
||||
export default request
|
||||
|
|
@ -0,0 +1,231 @@
|
|||
// 纯视图模型:不 import React、不触碰 DOM,可被 node 直接 import 测试。
|
||||
// 依据 CONTRACT.md「Web 工作台」一节生成 buildWorkbenchView(view, ui) 的返回结构;
|
||||
// 十席名称 / 职责全文一律取自共享的 src/shared/roles.js,保证三端一致。
|
||||
|
||||
import { SEATS, SEAT_IDS, SEAT_GROUPS } from '../shared/roles.js'
|
||||
|
||||
// 未选择模型时的固定文案,两端 UI 必须一致。
|
||||
export const UNCHOSEN_MODEL_LABEL = '请选择模型'
|
||||
|
||||
export const SEAT_STATUS_LABELS = Object.freeze({
|
||||
pending: '待启用',
|
||||
creating: '创建中',
|
||||
bound: '已绑定',
|
||||
failed: '创建失败',
|
||||
missing: '会话缺失',
|
||||
})
|
||||
|
||||
const DEFAULT_SEAT_STATUS = 'pending'
|
||||
|
||||
export function seatStatusLabel(status) {
|
||||
if (typeof status !== 'string') return '未知状态'
|
||||
return SEAT_STATUS_LABELS[status] ?? '未知状态'
|
||||
}
|
||||
|
||||
export function projectStatusLabel(status) {
|
||||
switch (status) {
|
||||
case 'pending': return '待启用'
|
||||
case 'provisioning': return '启用中'
|
||||
case 'ready': return '已启用'
|
||||
case 'error': return '启用失败'
|
||||
default: return '未知状态'
|
||||
}
|
||||
}
|
||||
|
||||
// 把 models 端点返回的目录摊平成下拉选项。value 形如 provider::model[::effort],
|
||||
// 永远不等于 'inherit'(界面不提供“跟随宿主模型”)。
|
||||
export function collectModelOptions(models) {
|
||||
const out = []
|
||||
const seen = new Set()
|
||||
const providers = Array.isArray(models?.providers) ? models.providers : []
|
||||
for (const entry of providers) {
|
||||
const provider = typeof entry?.provider === 'string' ? entry.provider : ''
|
||||
if (!provider) continue
|
||||
const list = Array.isArray(entry?.models) ? entry.models : []
|
||||
for (const item of list) {
|
||||
const model = typeof item?.model === 'string' ? item.model : ''
|
||||
if (!model) continue
|
||||
const efforts = Array.isArray(item?.reasoningEffort)
|
||||
? item.reasoningEffort.filter(e => typeof e === 'string' && e.trim() !== '')
|
||||
: []
|
||||
if (efforts.length > 0) {
|
||||
for (const effort of efforts) {
|
||||
const value = provider + '::' + model + '::' + effort
|
||||
if (value === 'inherit' || seen.has(value)) continue
|
||||
seen.add(value)
|
||||
out.push({ value, label: model + ' · ' + effort, provider, model, reasoningEffort: effort })
|
||||
}
|
||||
} else {
|
||||
const value = provider + '::' + model
|
||||
if (value === 'inherit' || seen.has(value)) continue
|
||||
seen.add(value)
|
||||
out.push({ value, label: model, provider, model })
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export function findModelOption(options, modelValue) {
|
||||
if (!Array.isArray(options)) return undefined
|
||||
return options.find(option => option.value === modelValue)
|
||||
}
|
||||
|
||||
// 把某个席已保存的 model 对象映射成 { modelValue, modelLabel }。
|
||||
export function describeModel(model, options) {
|
||||
if (!model || typeof model !== 'object' || typeof model.provider !== 'string' || typeof model.model !== 'string') {
|
||||
return { modelValue: '', modelLabel: UNCHOSEN_MODEL_LABEL }
|
||||
}
|
||||
const effort = typeof model.reasoningEffort === 'string' && model.reasoningEffort ? model.reasoningEffort : undefined
|
||||
const match = (Array.isArray(options) ? options : []).find(option =>
|
||||
option.provider === model.provider
|
||||
&& option.model === model.model
|
||||
&& (option.reasoningEffort ?? undefined) === effort)
|
||||
if (match) return { modelValue: match.value, modelLabel: match.label }
|
||||
const modelLabel = effort ? model.model + ' · ' + effort : model.model
|
||||
const modelValue = effort
|
||||
? model.provider + '::' + model.model + '::' + effort
|
||||
: model.provider + '::' + model.model
|
||||
return { modelValue, modelLabel }
|
||||
}
|
||||
|
||||
// 兼容两种入参:CONTRACT 的项目视图用数组;共享 schema 里可能以 seatId 为键。
|
||||
function normalizeSeats(seats) {
|
||||
const map = {}
|
||||
if (Array.isArray(seats)) {
|
||||
for (const seat of seats) {
|
||||
if (seat && typeof seat === 'object' && typeof seat.id === 'string') map[seat.id] = seat
|
||||
}
|
||||
} else if (seats && typeof seats === 'object') {
|
||||
for (const [id, seat] of Object.entries(seats)) {
|
||||
if (seat && typeof seat === 'object') map[id] = { id, ...seat }
|
||||
}
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
function cloneGroups() {
|
||||
const out = {}
|
||||
for (const key of Object.keys(SEAT_GROUPS)) out[key] = Array.from(SEAT_GROUPS[key])
|
||||
return out
|
||||
}
|
||||
|
||||
function pickSelectedId(requested) {
|
||||
if (typeof requested === 'string' && SEAT_IDS.includes(requested)) return requested
|
||||
return SEAT_IDS[0]
|
||||
}
|
||||
|
||||
function hasOwn(obj, key) {
|
||||
return obj !== null && obj !== undefined && Object.prototype.hasOwnProperty.call(obj, key)
|
||||
}
|
||||
|
||||
export function draftOf(draft, seatId) {
|
||||
if (!draft || typeof draft !== 'object') return {}
|
||||
const entry = draft[seatId]
|
||||
return entry && typeof entry === 'object' ? entry : {}
|
||||
}
|
||||
|
||||
// 返回新的草稿映射(不可变):保留其它席的草稿,便于“切换角色不丢草稿”。
|
||||
export function updateDraft(draft, seatId, patch) {
|
||||
const base = draft && typeof draft === 'object' ? draft : {}
|
||||
const previous = base[seatId] && typeof base[seatId] === 'object' ? base[seatId] : {}
|
||||
return { ...base, [seatId]: { ...previous, ...(patch ?? {}) } }
|
||||
}
|
||||
|
||||
export function clearDraft(draft, seatId) {
|
||||
if (!draft || typeof draft !== 'object' || !hasOwn(draft, seatId)) return draft ?? {}
|
||||
const next = { ...draft }
|
||||
delete next[seatId]
|
||||
return next
|
||||
}
|
||||
|
||||
export function buildWorkbenchView(view, ui) {
|
||||
const safeView = view && typeof view === 'object' ? view : {}
|
||||
const project = safeView.project && typeof safeView.project === 'object' ? safeView.project : {}
|
||||
const status = typeof project.status === 'string' ? project.status : 'pending'
|
||||
const ready = status === 'ready'
|
||||
const seatMap = normalizeSeats(project.seats)
|
||||
const selectedSeatId = pickSelectedId(ui?.selectedSeatId)
|
||||
const models = ui?.models ?? null
|
||||
const modelOptions = collectModelOptions(models)
|
||||
const draft = ui?.draft ?? null
|
||||
|
||||
const seats = SEAT_IDS.map(id => {
|
||||
const def = SEATS[id]
|
||||
const rec = seatMap[id] ?? {}
|
||||
const seatStatus = typeof rec.status === 'string' ? rec.status : DEFAULT_SEAT_STATUS
|
||||
return {
|
||||
id,
|
||||
name: def.label,
|
||||
duty: def.duty,
|
||||
status: seatStatus,
|
||||
statusLabel: seatStatusLabel(seatStatus),
|
||||
selected: id === selectedSeatId,
|
||||
}
|
||||
})
|
||||
|
||||
const seatDef = SEATS[selectedSeatId]
|
||||
const seatRec = seatMap[selectedSeatId] ?? {}
|
||||
const draftEntry = draftOf(draft, selectedSeatId)
|
||||
let described
|
||||
if (hasOwn(draftEntry, 'modelValue')) {
|
||||
const raw = draftEntry.modelValue
|
||||
if (raw === '' || raw === null || raw === undefined) {
|
||||
described = { modelValue: '', modelLabel: UNCHOSEN_MODEL_LABEL }
|
||||
} else {
|
||||
const match = findModelOption(modelOptions, raw)
|
||||
described = match
|
||||
? { modelValue: match.value, modelLabel: match.label }
|
||||
: { modelValue: String(raw), modelLabel: String(raw) }
|
||||
}
|
||||
} else if (hasOwn(draftEntry, 'model')) {
|
||||
described = describeModel(draftEntry.model, modelOptions)
|
||||
} else {
|
||||
described = describeModel(seatRec.model ?? null, modelOptions)
|
||||
}
|
||||
|
||||
const instructions = hasOwn(draftEntry, 'instructions')
|
||||
? draftEntry.instructions
|
||||
: (typeof seatRec.instructions === 'string' ? seatRec.instructions : '')
|
||||
const selectedStatus = typeof seatRec.status === 'string' ? seatRec.status : DEFAULT_SEAT_STATUS
|
||||
|
||||
let boundCount = 0
|
||||
let sessionCount = 0
|
||||
for (const id of SEAT_IDS) {
|
||||
const rec = seatMap[id]
|
||||
if (rec?.status === 'bound') boundCount += 1
|
||||
if (rec?.sessionId) sessionCount += 1
|
||||
}
|
||||
|
||||
return {
|
||||
projectTitle: typeof project.name === 'string' ? project.name : '',
|
||||
ready,
|
||||
project: {
|
||||
id: project.id ?? '',
|
||||
name: typeof project.name === 'string' ? project.name : '',
|
||||
status,
|
||||
statusLabel: projectStatusLabel(status),
|
||||
workspaceId: project.workspaceId ?? null,
|
||||
path: project.path ?? null,
|
||||
seatCount: seats.length,
|
||||
boundCount,
|
||||
sessionCount,
|
||||
},
|
||||
seats,
|
||||
groups: cloneGroups(),
|
||||
selected: {
|
||||
id: selectedSeatId,
|
||||
name: seatDef.label,
|
||||
duty: seatDef.duty,
|
||||
responsibility: seatDef.responsibility,
|
||||
status: selectedStatus,
|
||||
statusLabel: seatStatusLabel(selectedStatus),
|
||||
sessionId: seatRec.sessionId ?? null,
|
||||
modelValue: described.modelValue,
|
||||
modelLabel: described.modelLabel,
|
||||
instructions,
|
||||
modelOptions,
|
||||
dirty: Object.keys(draftEntry).length > 0,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
import { SEAT_IDS } from '../shared/roles.js'
|
||||
|
||||
function bad(message, code = 'sansheng/invalid') {
|
||||
const error = new Error(message)
|
||||
error.code = code
|
||||
return error
|
||||
}
|
||||
function requireProjectId(payload) {
|
||||
const id = payload?.projectId
|
||||
if (typeof id !== 'string' || id.trim() === '') throw bad('缺少 projectId')
|
||||
return id
|
||||
}
|
||||
|
||||
// 生成 POST /api/sansheng 的处理函数:{endpoint,payload} -> {ok,value}|{ok,error}
|
||||
export function createApiHandler(service) {
|
||||
return async function handle(endpoint, payload) {
|
||||
try {
|
||||
switch (endpoint) {
|
||||
case 'list':
|
||||
return { ok: true, value: await service.list() }
|
||||
case 'project':
|
||||
return { ok: true, value: await service.project(requireProjectId(payload)) }
|
||||
case 'open':
|
||||
return { ok: true, value: await service.open(payload ?? {}) }
|
||||
case 'enable':
|
||||
return { ok: true, value: await service.enable(requireProjectId(payload)) }
|
||||
case 'configure': {
|
||||
const projectId = requireProjectId(payload)
|
||||
const seatId = payload?.seatId
|
||||
if (!SEAT_IDS.includes(seatId)) throw bad(`未知席 ${String(seatId)}`)
|
||||
return { ok: true, value: await service.configure(projectId, seatId, { model: payload?.model, instructions: payload?.instructions }) }
|
||||
}
|
||||
case 'models':
|
||||
return { ok: true, value: await service.models() }
|
||||
default:
|
||||
throw bad(`未知 endpoint ${String(endpoint)}`)
|
||||
}
|
||||
} catch (error) {
|
||||
return { ok: false, error: { code: error?.code ?? 'sansheng/error', message: error?.message ?? String(error) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
export const ROUTE = '/api/sansheng'
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
// 模型配置:只记录会话级 model/selection 事件,绝不写 profile 全局默认。
|
||||
// 关键约束:不调用 sessionController.selectModel / saveSelection(它们会改全局默认)。
|
||||
export class ModelError extends Error {
|
||||
constructor(code, message) { super(message); this.name = 'ModelError'; this.code = code }
|
||||
}
|
||||
|
||||
export function normalizeSelection(selection) {
|
||||
if (selection === null || selection === undefined) return null
|
||||
if (typeof selection !== 'object') throw new ModelError('sansheng/model-invalid', '模型选择必须是对象或 null')
|
||||
const { provider, model, reasoningEffort } = selection
|
||||
if (typeof provider !== 'string' || provider.trim() === '') throw new ModelError('sansheng/model-invalid', '缺少 provider')
|
||||
if (typeof model !== 'string' || model.trim() === '') throw new ModelError('sansheng/model-invalid', '缺少 model')
|
||||
const out = { provider, model }
|
||||
if (reasoningEffort !== undefined && reasoningEffort !== null && reasoningEffort !== '') out.reasoningEffort = reasoningEffort
|
||||
return out
|
||||
}
|
||||
|
||||
// 对一个已绑定会话应用模型选择。返回 agent.model.current()。
|
||||
export async function applyModel(host, sessionId, selection) {
|
||||
const normalized = normalizeSelection(selection)
|
||||
if (!normalized) return null
|
||||
const resolved = await host.sessionController.resolveAgent(sessionId)
|
||||
if (!resolved || (resolved && 'error' in resolved)) {
|
||||
const err = resolved?.error
|
||||
throw new ModelError('sansheng/unbound', `会话不可用:${err?.message ?? err?.code ?? 'resolve failed'}`)
|
||||
}
|
||||
const agent = resolved.agent
|
||||
// 用 llm 校验路由/思考强度,不能只依赖 select 的字符串。
|
||||
await host.llm.resolveCallConfig(normalized)
|
||||
// 复核对象仍是此 ID 的活跃 Agent。
|
||||
if (host.agents.get(sessionId) !== agent) throw new ModelError('sansheng/conflict', '配置期间 Agent 已变化')
|
||||
agent.model.select(normalized)
|
||||
return agent.model.current()
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
/** DSH 主目录,与宿主一致:优先 DSH_HOME,否则 ~/.dsh。 */
|
||||
export function dshHome(env = process.env) {
|
||||
const fromEnv = env.DSH_HOME
|
||||
if (typeof fromEnv === 'string' && fromEnv.trim() !== '') return fromEnv
|
||||
return join(homedir(), '.dsh')
|
||||
}
|
||||
|
||||
/** 三省六部自己的项目状态文件;与用户其它 DSH 数据分开存放。 */
|
||||
export function sanshengStatePath(home = dshHome()) {
|
||||
return join(home, 'sansheng', 'state.json')
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
import { seatBySessionId } from '../shared/roles.js'
|
||||
|
||||
export const PROMPT_SECTION = 'sansheng'
|
||||
|
||||
export function renderSeatPrompt({ project, seatId, seat }) {
|
||||
const lines = [
|
||||
`你在「${project?.name ?? project?.id ?? '当前项目'}」项目中担任${seat.label}(${seatId})。`,
|
||||
`本席职责:${seat.responsibility}`,
|
||||
]
|
||||
const note = project?.seats?.[seatId]?.instructions
|
||||
if (typeof note === 'string' && note.trim() !== '') lines.push(`补充说明:${note.trim()}`)
|
||||
lines.push('只在本项目本席会话内工作;不要修改其他项目或其他席的配置,也不要替用户提升权限。')
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
// 注册动态 systemPrompt section:只对十席会话注入本席角色文本,其它会话返回空串。
|
||||
export function installPromptSection(ctx, { store }) {
|
||||
return ctx.systemPrompt.section({
|
||||
name: PROMPT_SECTION,
|
||||
order: 60,
|
||||
interpolate: false,
|
||||
text: context => {
|
||||
const sessionId = context?.agent?.id
|
||||
if (!sessionId) return ''
|
||||
const found = seatBySessionId(store.state?.projects, sessionId)
|
||||
if (!found) return ''
|
||||
return renderSeatPrompt({ project: found.project, seatId: found.seatId, seat: found.seat })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,154 @@
|
|||
// 严格会话创建/恢复:先持久化计划 ID,再查是否已存在,只创建缺失项;
|
||||
// ID 不一致立即停止后续创建并保留记录;失败保留已完成绑定,重试只补未完成项。
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { SEAT_IDS, SEATS } from '../shared/roles.js'
|
||||
|
||||
export class ProvisionError extends Error {
|
||||
constructor(code, message) { super(message); this.name = 'ProvisionError'; this.code = code }
|
||||
}
|
||||
|
||||
function isNotFound(error) {
|
||||
if (!error) return false
|
||||
const code = String(error.code ?? '')
|
||||
if (/not.?found/i.test(code)) return true
|
||||
const message = String(error.message ?? '')
|
||||
return /not.?found|不存在|ENOENT/i.test(message)
|
||||
}
|
||||
|
||||
export function createProvisioner({ store, host, now = () => Date.now() }) {
|
||||
const locks = new Map()
|
||||
|
||||
function withLock(key, fn) {
|
||||
const prev = locks.get(key) ?? Promise.resolve()
|
||||
const run = prev.then(fn, fn)
|
||||
const guarded = run.finally(() => { if (locks.get(key) === guarded) locks.delete(key) })
|
||||
locks.set(key, guarded)
|
||||
return guarded
|
||||
}
|
||||
|
||||
async function markBound(projectId, seatId, sessionId) {
|
||||
await store.mutate(s => {
|
||||
const p = s.projects[projectId]
|
||||
const st = p.seats[seatId]
|
||||
st.sessionId = sessionId
|
||||
st.status = 'bound'
|
||||
st.error = null
|
||||
st.updatedAt = now()
|
||||
p.updatedAt = now()
|
||||
})
|
||||
}
|
||||
async function markFailed(projectId, seatId, message) {
|
||||
await store.mutate(s => {
|
||||
const st = s.projects[projectId].seats[seatId]
|
||||
st.status = 'failed'
|
||||
st.error = String(message)
|
||||
st.updatedAt = now()
|
||||
})
|
||||
}
|
||||
async function markMismatch(projectId, seatId, planned, actual) {
|
||||
await store.mutate(s => {
|
||||
const st = s.projects[projectId].seats[seatId]
|
||||
st.status = 'failed'
|
||||
st.error = `会话 ID 不一致:计划 ${planned},实际 ${actual ?? 'null'};已停止后续创建,请核对`
|
||||
st.updatedAt = now()
|
||||
})
|
||||
}
|
||||
|
||||
async function ensureSeat(projectId, seatId) {
|
||||
await store.ensureLoaded()
|
||||
const seat = store.get(projectId).seats[seatId]
|
||||
if (seat.status === 'bound' && seat.sessionId) return { ok: true, skipped: true }
|
||||
|
||||
// 先持久化计划 sessionId 与 creating 状态,再发起宿主调用。
|
||||
await store.mutate(s => {
|
||||
const st = s.projects[projectId].seats[seatId]
|
||||
if (!st.plannedSessionId) st.plannedSessionId = randomUUID()
|
||||
st.status = 'creating'
|
||||
st.error = null
|
||||
st.updatedAt = now()
|
||||
s.projects[projectId].updatedAt = now()
|
||||
})
|
||||
const project = store.get(projectId)
|
||||
const planned = project.seats[seatId].plannedSessionId
|
||||
|
||||
// 已存在则不重建,按既有会话恢复绑定。
|
||||
let resolved
|
||||
try { resolved = await host.sessionController.resolveAgent(planned) } catch (error) {
|
||||
await markFailed(projectId, seatId, `resolve: ${error?.message ?? error}`)
|
||||
return { ok: false }
|
||||
}
|
||||
if (resolved && !('error' in resolved) && resolved.agent) {
|
||||
await markBound(projectId, seatId, planned)
|
||||
return { ok: true, recovered: true }
|
||||
}
|
||||
if (resolved && 'error' in resolved && resolved.error && !isNotFound(resolved.error)) {
|
||||
await markFailed(projectId, seatId, `resolve: ${resolved.error?.message ?? resolved.error?.code ?? 'error'}`)
|
||||
return { ok: false }
|
||||
}
|
||||
|
||||
// 创建缺失项。返回 ID 必须与计划一致,否则保留实际 ID 并停止后续创建。
|
||||
let returned
|
||||
try {
|
||||
returned = await host.sessionController.create({ sessionId: planned, workspaceId: project.workspaceId ?? undefined })
|
||||
} catch (error) {
|
||||
await markFailed(projectId, seatId, `create: ${error?.message ?? error}`)
|
||||
return { ok: false }
|
||||
}
|
||||
if (!returned || returned.sessionId !== planned) {
|
||||
await markMismatch(projectId, seatId, planned, returned?.sessionId ?? null)
|
||||
return { ok: false, fatal: true }
|
||||
}
|
||||
await markBound(projectId, seatId, planned)
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
async function enable(projectId) {
|
||||
return withLock(projectId, async () => {
|
||||
await store.ensureLoaded()
|
||||
const project = store.get(projectId)
|
||||
if (!project) throw new ProvisionError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||
await store.mutate(s => {
|
||||
const p = s.projects[projectId]
|
||||
p.status = 'provisioning'
|
||||
p.updatedAt = now()
|
||||
p.revision = (p.revision ?? 0) + 1
|
||||
})
|
||||
let fatal = false
|
||||
for (const seatId of SEAT_IDS) {
|
||||
const result = await ensureSeat(projectId, seatId)
|
||||
if (result.fatal) { fatal = true; break }
|
||||
}
|
||||
|
||||
// 预热:把每个已绑定会话加载一次(resolveAgent 会 resume 冷会话并生成 summary),
|
||||
// 否则 DSH 左侧工作区会话树(orderByRecency 依赖 summary)会跳过这些会话不显示。
|
||||
if (typeof host.sessionController.resolveAgent === 'function') {
|
||||
for (const seatId of SEAT_IDS) {
|
||||
const seat = store.get(projectId)?.seats?.[seatId]
|
||||
if (!seat || !seat.sessionId || seat.status !== 'bound') continue
|
||||
try { await host.sessionController.resolveAgent(seat.sessionId) } catch { /* 预热失败不影响绑定 */ }
|
||||
}
|
||||
}
|
||||
|
||||
// 给每个已绑定会话写标题(如“丞相会话”),让左侧工作区列表能收录并显示为独立对话。
|
||||
if (typeof host.sessionController.rename === 'function') {
|
||||
for (const seatId of SEAT_IDS) {
|
||||
const seat = store.get(projectId)?.seats?.[seatId]
|
||||
if (!seat || !seat.sessionId || seat.status !== 'bound') continue
|
||||
try {
|
||||
await host.sessionController.rename({ sessionId: seat.sessionId, title: `${SEATS[seatId].label}会话` })
|
||||
} catch { /* 标题失败不影响绑定;下次启用会重试 */ }
|
||||
}
|
||||
}
|
||||
await store.mutate(s => {
|
||||
const p = s.projects[projectId]
|
||||
const allBound = SEAT_IDS.every(id => p.seats[id].status === 'bound')
|
||||
p.status = allBound ? 'ready' : 'error'
|
||||
p.updatedAt = now()
|
||||
p.revision = (p.revision ?? 0) + 1
|
||||
})
|
||||
return { projectId, fatal }
|
||||
})
|
||||
}
|
||||
|
||||
return { enable, ensureSeat }
|
||||
}
|
||||
|
|
@ -0,0 +1,159 @@
|
|||
import { SEAT_IDS, SEATS, SEAT_GROUPS } from '../shared/roles.js'
|
||||
import { applyModel, normalizeSelection } from './model.js'
|
||||
|
||||
export class ServiceError extends Error {
|
||||
constructor(code, message) { super(message); this.name = 'ServiceError'; this.code = code }
|
||||
}
|
||||
|
||||
export function seatView(seatId, seat) {
|
||||
const def = SEATS[seatId]
|
||||
return {
|
||||
id: seatId,
|
||||
label: def.label,
|
||||
duty: def.duty,
|
||||
responsibility: def.responsibility,
|
||||
status: seat.status,
|
||||
sessionId: seat.sessionId ?? null,
|
||||
model: seat.model ?? null,
|
||||
instructions: seat.instructions ?? '',
|
||||
error: seat.error ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
export function projectView(project) {
|
||||
return {
|
||||
revision: project.revision ?? 0,
|
||||
project: {
|
||||
id: project.id,
|
||||
name: project.name,
|
||||
workspaceId: project.workspaceId ?? null,
|
||||
path: project.path ?? null,
|
||||
status: project.status,
|
||||
seats: SEAT_IDS.map(id => seatView(id, project.seats[id])),
|
||||
groups: {
|
||||
lead: [...SEAT_GROUPS.lead],
|
||||
sansheng: [...SEAT_GROUPS.sansheng],
|
||||
liubu: [...SEAT_GROUPS.liubu],
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeCatalog(catalog) {
|
||||
const providers = []
|
||||
const entryFor = provider => {
|
||||
let entry = providers.find(p => p.provider === provider)
|
||||
if (!entry) { entry = { provider, models: [] }; providers.push(entry) }
|
||||
return entry
|
||||
}
|
||||
const groups = catalog?.providers ?? catalog?.groups ?? catalog?.entries ?? []
|
||||
if (Array.isArray(groups)) {
|
||||
for (const g of groups) {
|
||||
const provider = g?.provider ?? g?.id ?? g?.ref ?? g?.name
|
||||
const list = g?.models ?? g?.entries ?? []
|
||||
for (const m of Array.isArray(list) ? list : []) {
|
||||
const modelId = typeof m === 'string' ? m : (m?.model ?? m?.id ?? m?.name)
|
||||
if (!provider || !modelId) continue
|
||||
const entry = entryFor(provider)
|
||||
if (entry.models.some(x => x.model === modelId)) continue
|
||||
const effort = typeof m === 'object' ? (m.reasoningEffort ?? m.reasoning) : undefined
|
||||
entry.models.push(effort ? { model: modelId, reasoningEffort: effort } : { model: modelId })
|
||||
}
|
||||
}
|
||||
}
|
||||
const def = catalog?.default ?? catalog?.deploymentDefault ?? null
|
||||
return {
|
||||
providers,
|
||||
default: def && (def.provider || def.model) ? { provider: def.provider ?? null, model: def.model ?? null } : null,
|
||||
failures: catalog?.failures ?? catalog?.isolated ?? [],
|
||||
}
|
||||
}
|
||||
|
||||
export class SanshengService {
|
||||
constructor({ store, host, provisioner }) {
|
||||
this.store = store
|
||||
this.host = host
|
||||
this.provisioner = provisioner
|
||||
}
|
||||
|
||||
async list() {
|
||||
await this.store.ensureLoaded()
|
||||
return {
|
||||
projects: [...this.store.list()]
|
||||
.sort((a, b) => String(a.name).localeCompare(String(b.name), 'zh-Hans-CN'))
|
||||
.map(p => ({ id: p.id, name: p.name, status: p.status, revision: p.revision ?? 0 })),
|
||||
}
|
||||
}
|
||||
|
||||
async open({ workspaceId, name, path } = {}) {
|
||||
await this.store.ensureLoaded()
|
||||
if (!workspaceId && !path) throw new ServiceError('sansheng/invalid', '需要 workspaceId 或 path')
|
||||
const registry = this.host.workspaceRegistry
|
||||
let ws
|
||||
if (workspaceId) {
|
||||
ws = registry.get(workspaceId)
|
||||
if (!ws) throw new ServiceError('sansheng/not-found', `未找到工作区 ${workspaceId}`)
|
||||
} else {
|
||||
ws = await registry.resolveByPath(path)
|
||||
if (!ws) ws = await registry.create(path, name)
|
||||
}
|
||||
const id = ws.id ?? ws.workspaceId
|
||||
await this.store.mutate(() => {
|
||||
this.store.ensureProjectRecord({
|
||||
id,
|
||||
name: name ?? ws.title ?? ws.name ?? id,
|
||||
workspaceId: id,
|
||||
path: ws.path ?? path ?? null,
|
||||
})
|
||||
})
|
||||
return projectView(this.store.get(id))
|
||||
}
|
||||
|
||||
async project(projectId) {
|
||||
await this.store.ensureLoaded()
|
||||
const p = this.store.get(projectId)
|
||||
if (!p) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||
return projectView(p)
|
||||
}
|
||||
|
||||
async enable(projectId) {
|
||||
await this.store.ensureLoaded()
|
||||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||
await this.provisioner.enable(projectId)
|
||||
return this.project(projectId)
|
||||
}
|
||||
|
||||
async configure(projectId, seatId, { model, instructions } = {}) {
|
||||
await this.store.ensureLoaded()
|
||||
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/invalid', `未知席 ${seatId}`)
|
||||
const project = this.store.get(projectId)
|
||||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||
const seat = project.seats[seatId]
|
||||
|
||||
let normalized
|
||||
let applied = null
|
||||
if (model !== undefined) {
|
||||
normalized = normalizeSelection(model) // 可能抛 sansheng/model-invalid
|
||||
if (seat.sessionId) applied = await applyModel(this.host, seat.sessionId, normalized)
|
||||
}
|
||||
if (instructions !== undefined && typeof instructions !== 'string') {
|
||||
throw new ServiceError('sansheng/invalid', 'instructions 必须是字符串')
|
||||
}
|
||||
|
||||
await this.store.mutate(s => {
|
||||
const target = s.projects[projectId].seats[seatId]
|
||||
if (model !== undefined) target.model = normalized
|
||||
if (instructions !== undefined) target.instructions = instructions
|
||||
target.updatedAt = Date.now()
|
||||
s.projects[projectId].updatedAt = Date.now()
|
||||
s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1
|
||||
})
|
||||
return { seat: seatView(seatId, this.store.get(projectId).seats[seatId]), applied }
|
||||
}
|
||||
|
||||
async models() {
|
||||
await this.store.ensureLoaded()
|
||||
const catalog = await this.host.sessionController.modelCatalog()
|
||||
return normalizeCatalog(catalog)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
// 项目状态存储:单个 JSON 文件,原子写,读取时严格校验;损坏不静默回退。
|
||||
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
||||
import { dirname } from 'node:path'
|
||||
import { emptyState, emptyProject, validateState } from '../shared/schema.js'
|
||||
import { seatBySessionId } from '../shared/roles.js'
|
||||
|
||||
export class StoreError extends Error {
|
||||
constructor(code, message) { super(message); this.name = 'StoreError'; this.code = code }
|
||||
}
|
||||
|
||||
export class SanshengStore {
|
||||
constructor(file) {
|
||||
this.file = file
|
||||
this.state = emptyState()
|
||||
this._queue = Promise.resolve()
|
||||
this._loaded = false
|
||||
this._loadPromise = null
|
||||
}
|
||||
|
||||
// 惰性加载:插件 apply 必须同步返回,真实 HTTP 请求到达时再确保状态已读入。
|
||||
ensureLoaded() {
|
||||
if (this._loaded) return Promise.resolve()
|
||||
if (!this._loadPromise) {
|
||||
this._loadPromise = this.load().catch(error => { this._loadPromise = null; throw error })
|
||||
}
|
||||
return this._loadPromise
|
||||
}
|
||||
|
||||
async load() {
|
||||
let raw
|
||||
try {
|
||||
raw = await readFile(this.file, 'utf8')
|
||||
} catch (error) {
|
||||
if (error?.code === 'ENOENT') { this.state = emptyState(); this._loaded = true; return }
|
||||
throw new StoreError('sansheng/state-corrupt', `无法读取状态文件:${error?.message ?? error}`)
|
||||
}
|
||||
let parsed
|
||||
try { parsed = JSON.parse(raw) } catch (error) {
|
||||
throw new StoreError('sansheng/state-corrupt', `状态文件不是合法 JSON:${error.message}`)
|
||||
}
|
||||
const valid = validateState(parsed)
|
||||
if (!valid.ok) throw new StoreError('sansheng/state-corrupt', `状态文件损坏:${valid.error}`)
|
||||
this.state = valid.state
|
||||
this._loaded = true
|
||||
}
|
||||
|
||||
snapshot() { return structuredClone(this.state) }
|
||||
get(projectId) { return this.state.projects[projectId] }
|
||||
list() { return Object.values(this.state.projects) }
|
||||
seatBySession(sessionId) { return seatBySessionId(this.state.projects, sessionId) }
|
||||
|
||||
// 所有写操作经此串行化:同一时刻只有一个 mutate 在跑,失败回滚内存状态。
|
||||
async mutate(fn) {
|
||||
const run = async () => {
|
||||
await this.ensureLoaded()
|
||||
const before = structuredClone(this.state)
|
||||
try {
|
||||
const result = await fn(this.state)
|
||||
this.state.seq = (this.state.seq ?? 0) + 1
|
||||
await this.save()
|
||||
return result
|
||||
} catch (error) {
|
||||
this.state = before
|
||||
throw error
|
||||
}
|
||||
}
|
||||
this._queue = this._queue.then(run, run)
|
||||
return this._queue
|
||||
}
|
||||
|
||||
async save() {
|
||||
await mkdir(dirname(this.file), { recursive: true })
|
||||
const tmp = `${this.file}.${process.pid}.${Date.now()}.tmp`
|
||||
await writeFile(tmp, JSON.stringify(this.state, null, 2), 'utf8')
|
||||
await rename(tmp, this.file)
|
||||
}
|
||||
|
||||
// 确保项目记录存在;已存在则只补空字段,不覆盖既有会话/配置。
|
||||
ensureProjectRecord({ id, name, workspaceId = null, path = null, now = Date.now() }) {
|
||||
let project = this.state.projects[id]
|
||||
if (!project) {
|
||||
project = emptyProject({ id, name: name ?? id, workspaceId, path, now })
|
||||
this.state.projects[id] = project
|
||||
return project
|
||||
}
|
||||
if (name && !project.name) project.name = name
|
||||
if (workspaceId && !project.workspaceId) project.workspaceId = workspaceId
|
||||
if (path && !project.path) project.path = path
|
||||
project.updatedAt = now
|
||||
project.revision = (project.revision ?? 0) + 1
|
||||
return project
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,201 @@
|
|||
// dsh-go 原生接入:把纯视图树挂到宿主原生面板桥。
|
||||
// 全程用特性探测(ctx.inject + typeof 检查),不 import 宿主内部源码。
|
||||
import { buildPanelView } from './panel.js'
|
||||
import { SEAT_IDS } from '../shared/roles.js'
|
||||
|
||||
const PANEL_ID = 'sansheng'
|
||||
|
||||
// 进程内缓存:原生作用域没有 workspaceId,只能由 sessionId 反查项目。
|
||||
// 真实数据源需要宿主注入的服务或 HTTP 接通;拿不到时视图如实显示提示。
|
||||
const viewBySession = new Map()
|
||||
const selectionBySession = new Map()
|
||||
const modelsBySession = new Map()
|
||||
|
||||
/** 把一个项目视图中各席的 sessionId 记入缓存,供 scope.sessionId 反查。 */
|
||||
function cacheProject(project) {
|
||||
if (!project || typeof project !== 'object') return
|
||||
const seats = project.seats
|
||||
for (const id of SEAT_IDS) {
|
||||
let seat = null
|
||||
if (Array.isArray(seats)) seat = seats.find((s) => s && s.id === id) || null
|
||||
else if (seats && typeof seats === 'object') seat = seats[id] || null
|
||||
if (seat && typeof seat.sessionId === 'string' && seat.sessionId) {
|
||||
viewBySession.set(seat.sessionId, project)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 由 scope 反查项目视图:优先宿主注入的反查服务,其次 sessions.binding,最后进程内缓存。 */
|
||||
function resolveProject(native, scope) {
|
||||
const sid = scope && typeof scope.sessionId === 'string' ? scope.sessionId : null
|
||||
const lookup = (native && (native.sansheng || native.sanshengProjects)) || null
|
||||
|
||||
if (lookup && typeof lookup.projectForScope === 'function') {
|
||||
try {
|
||||
const p = lookup.projectForScope(scope)
|
||||
if (p) { cacheProject(p); return p }
|
||||
} catch (e) { /* 特性探测失败,忽略 */ }
|
||||
}
|
||||
if (lookup && typeof lookup.projectForSession === 'function' && sid) {
|
||||
try {
|
||||
const p = lookup.projectForSession(sid)
|
||||
if (p) { cacheProject(p); return p }
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
let workspaceId = null
|
||||
try {
|
||||
const sessions = native && native.sessions
|
||||
if (sessions && typeof sessions.binding === 'function' && sid) {
|
||||
const b = sessions.binding(sid)
|
||||
workspaceId = (b && (b.workspaceId || (b.workspace && b.workspace.id))) || null
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
|
||||
if (lookup && typeof lookup.projectForWorkspace === 'function' && workspaceId) {
|
||||
try {
|
||||
const p = lookup.projectForWorkspace(workspaceId)
|
||||
if (p) { cacheProject(p); return p }
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
if (sid && viewBySession.has(sid)) return viewBySession.get(sid)
|
||||
return null
|
||||
}
|
||||
|
||||
/** 组装 buildPanelView 所需的 input。 */
|
||||
function makeView(native, scope) {
|
||||
const sid = scope && typeof scope.sessionId === 'string' ? scope.sessionId : null
|
||||
const project = resolveProject(native, scope)
|
||||
const selectedSeatId = sid && selectionBySession.has(sid) ? selectionBySession.get(sid) : null
|
||||
const models = sid && modelsBySession.has(sid) ? modelsBySession.get(sid) : null
|
||||
return buildPanelView({ project, selectedSeatId, models })
|
||||
}
|
||||
|
||||
/** 归一化事件里的 action(dsh-go 可能回传对象或字符串 + value)。 */
|
||||
function normalizeAction(event) {
|
||||
const a = event && event.action
|
||||
if (a && typeof a === 'object') return a
|
||||
const v = event && event.value
|
||||
if (v && typeof v === 'object' && typeof v.type === 'string') return v
|
||||
if (typeof a === 'string') return Object.assign({ type: a }, v && typeof v === 'object' ? v : {})
|
||||
return null
|
||||
}
|
||||
|
||||
async function handleEvent(native, scope, event) {
|
||||
const sid = scope && typeof scope.sessionId === 'string' ? scope.sessionId : null
|
||||
const action = normalizeAction(event)
|
||||
if (!action || typeof action.type !== 'string') return []
|
||||
|
||||
switch (action.type) {
|
||||
case 'sansheng/select-seat': {
|
||||
if (sid && action.seatId) selectionBySession.set(sid, action.seatId)
|
||||
return [{ type: 'refresh', id: PANEL_ID }]
|
||||
}
|
||||
case 'sansheng/select-model': {
|
||||
if (sid && action.seatId) selectionBySession.set(sid, action.seatId)
|
||||
// 模型持久化需要宿主 HTTP / 服务接通;原生面板暂不静默写入。
|
||||
return [{ type: 'toast', text: '模型选择在原生面板暂未接持久化,请在 Web 端保存(需真机核验)' }]
|
||||
}
|
||||
case 'sansheng/enter-session': {
|
||||
// effect 契约暂无会话跳转;优先探测宿主扩展方法,否则如实提示。
|
||||
const bridged = native && native.dshGo
|
||||
const open =
|
||||
(bridged && (bridged.openSession || bridged.navigate)) ||
|
||||
(native && native.sansheng && native.sansheng.openSession)
|
||||
if (typeof open === 'function' && action.sessionId) {
|
||||
try {
|
||||
await open(action.sessionId)
|
||||
return [{ type: 'toast', text: '已请求打开会话' }]
|
||||
} catch (e) { /* 落到提示分支 */ }
|
||||
}
|
||||
return [{ type: 'toast', text: '原生 effect 暂不支持会话跳转,请从宿主会话列表进入(需真机核验)' }]
|
||||
}
|
||||
default:
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** 可选 data 提供者:尽力通过宿主 HTTP 的 list/project 反查项目(特性探测 fetch)。 */
|
||||
function makeDataProvider(native, dshGo) {
|
||||
return function data(scope, emit) {
|
||||
let cancelled = false
|
||||
const run = async () => {
|
||||
if (typeof fetch !== 'function') return
|
||||
const sid = scope && typeof scope.sessionId === 'string' ? scope.sessionId : null
|
||||
if (!sid) return
|
||||
const post = async (endpoint, payload) => {
|
||||
const res = await fetch('/api/sansheng', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ endpoint, payload: payload == null ? null : payload }),
|
||||
})
|
||||
if (!res.ok) throw new Error('HTTP ' + res.status)
|
||||
const r = await res.json()
|
||||
if (!r || r.ok !== true) throw new Error((r && r.error && r.error.message) || 'request failed')
|
||||
return r.value
|
||||
}
|
||||
const list = await post('list')
|
||||
const projects = list && Array.isArray(list.projects) ? list.projects : []
|
||||
for (const meta of projects) {
|
||||
const value = await post('project', { projectId: meta.id })
|
||||
const project = value && value.project ? value.project : value
|
||||
cacheProject(project)
|
||||
const seats = project && project.seats
|
||||
const found = Array.isArray(seats)
|
||||
? seats.some((s) => s && s.sessionId === sid)
|
||||
: seats && Object.values(seats).some((s) => s && s.sessionId === sid)
|
||||
if (found) {
|
||||
if (!cancelled) {
|
||||
try { emit({ project }) } catch (e) { /* ignore */ }
|
||||
try { if (dshGo && typeof dshGo.refresh === 'function') dshGo.refresh(PANEL_ID, scope) } catch (e) { /* ignore */ }
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
run().catch(() => {})
|
||||
return () => { cancelled = true }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 原生接入入口。
|
||||
* @param {object} ctx Cordis context(由宿主注入)。
|
||||
* @returns {() => void} disposer
|
||||
*/
|
||||
export function install(ctx) {
|
||||
if (!ctx || typeof ctx.inject !== 'function') return () => {}
|
||||
|
||||
return ctx.inject(['dshGo', 'sessions'], (native) => {
|
||||
const dshGo = native && native.dshGo
|
||||
// 特性探测:宿主没有 dshGo.panel 就安静退出(不是 dsh-go / 桥未就绪)。
|
||||
if (!dshGo || typeof dshGo.panel !== 'function') return () => {}
|
||||
|
||||
const disposers = []
|
||||
|
||||
try {
|
||||
const offPanel = native.dshGo.panel(PANEL_ID, {
|
||||
view: (scope, caps) => makeView(native, scope),
|
||||
data: makeDataProvider(native, native.dshGo),
|
||||
})
|
||||
if (typeof offPanel === 'function') disposers.push(offPanel)
|
||||
} catch (e) { /* 桥不完整时保持静默 */ }
|
||||
|
||||
if (typeof native.dshGo.on === 'function') {
|
||||
try {
|
||||
const offOn = native.dshGo.on(PANEL_ID, (scope, event) => handleEvent(native, scope, event))
|
||||
if (typeof offOn === 'function') disposers.push(offOn)
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
return () => {
|
||||
for (const off of disposers) {
|
||||
try { off() } catch (e) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export default { install }
|
||||
|
|
@ -0,0 +1,198 @@
|
|||
// dsh-go 原生面板:纯视图树构造函数。
|
||||
// 仅依赖共享的角色定义(纯 JS),不 import 任何宿主 / React / DOM 代码。
|
||||
// 硬约束(在下方逻辑中自然满足,并由 test/native.test.js 断言):
|
||||
// 节点总数 ≤120、最大深度 ≤8、任何 options / items 列表 ≤8 项、无自由文本输入控件。
|
||||
import { SEATS, SEAT_IDS, SEAT_GROUPS } from '../shared/roles.js'
|
||||
|
||||
const GROUP_ORDER = ['lead', 'sansheng', 'liubu']
|
||||
const GROUP_TITLE = { lead: '统领', sansheng: '三省', liubu: '六部' }
|
||||
|
||||
const MAX_OPTIONS = 8 // 原生单选最多 8 项(含“请选择模型”占位)
|
||||
|
||||
const PROJECT_STATUS_TEXT = {
|
||||
pending: '待启用',
|
||||
provisioning: '启用中',
|
||||
ready: '已就绪',
|
||||
error: '异常',
|
||||
}
|
||||
|
||||
const SEAT_STATUS_TEXT = {
|
||||
pending: '待启用',
|
||||
creating: '创建中',
|
||||
bound: '已绑定',
|
||||
failed: '失败',
|
||||
missing: '缺失',
|
||||
}
|
||||
|
||||
function asText(v) {
|
||||
return typeof v === 'string' ? v : ''
|
||||
}
|
||||
|
||||
/** 兼容 project.seats 为数组(项目视图)或对象(内部状态)。 */
|
||||
function seatRecords(project) {
|
||||
const out = {}
|
||||
const seats = project ? project.seats : null
|
||||
if (Array.isArray(seats)) {
|
||||
for (const s of seats) if (s && SEATS[s.id]) out[s.id] = s
|
||||
} else if (seats && typeof seats === 'object') {
|
||||
for (const id of SEAT_IDS) if (seats[id]) out[id] = seats[id]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function isBound(seat) {
|
||||
return !!seat && typeof seat.sessionId === 'string' && seat.sessionId.length > 0
|
||||
}
|
||||
|
||||
function modelValue(model) {
|
||||
if (!model || typeof model !== 'object') return ''
|
||||
if (typeof model.provider !== 'string' || typeof model.model !== 'string') return ''
|
||||
return model.provider + '::' + model.model
|
||||
}
|
||||
|
||||
function flattenModels(models) {
|
||||
const opts = []
|
||||
const providers = models && Array.isArray(models.providers) ? models.providers : []
|
||||
for (const p of providers) {
|
||||
const pid = asText(p && p.provider)
|
||||
if (!pid) continue
|
||||
const list = Array.isArray(p && p.models) ? p.models : []
|
||||
for (const m of list) {
|
||||
const mid = typeof m === 'string' ? m : asText(m && m.model)
|
||||
if (!mid) continue
|
||||
opts.push({ value: pid + '::' + mid, label: pid + ' / ' + mid })
|
||||
if (opts.length >= MAX_OPTIONS - 1) break // 留一位给占位项
|
||||
}
|
||||
if (opts.length >= MAX_OPTIONS - 1) break
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
/** 模型原生单选:value 为空显示“请选择模型”。整体 ≤8 项。 */
|
||||
function buildModelSelect(project, seat, models) {
|
||||
const real = flattenModels(models)
|
||||
const options = [{ value: '', label: '请选择模型' }].concat(real).slice(0, MAX_OPTIONS)
|
||||
const want = modelValue(seat && seat.model)
|
||||
const value = options.some((o) => o.value === want) ? want : ''
|
||||
return {
|
||||
type: 'select',
|
||||
label: '模型',
|
||||
value,
|
||||
options,
|
||||
action: { type: 'sansheng/select-model', seatId: (seat && seat.id) || null, projectId: (project && project.id) || null },
|
||||
}
|
||||
}
|
||||
|
||||
/** 单个角色按钮:label 恰为两字;选中者高亮(selected + primary)。 */
|
||||
function seatButton(project, seat, selectedSeatId) {
|
||||
const meta = SEATS[seat.id]
|
||||
const selected = seat.id === selectedSeatId
|
||||
return {
|
||||
type: 'button',
|
||||
seatId: seat.id,
|
||||
label: meta.label,
|
||||
selected,
|
||||
variant: selected ? 'primary' : 'ghost',
|
||||
action: { type: 'sansheng/select-seat', seatId: seat.id, projectId: (project && project.id) || null },
|
||||
}
|
||||
}
|
||||
|
||||
/** 一个分组(stack):标题 + 若干 row,每行 ≤3 个角色按钮(六部拆两行)。 */
|
||||
function groupNode(project, records, key, selectedSeatId) {
|
||||
const ids = (SEAT_GROUPS[key] || []).filter((id) => records[id] && SEATS[id])
|
||||
if (ids.length === 0) return null
|
||||
const perRow = key === 'liubu' ? 3 : ids.length
|
||||
const rows = []
|
||||
for (let i = 0; i < ids.length; i += perRow) {
|
||||
const slice = ids.slice(i, i + perRow)
|
||||
rows.push({ type: 'row', children: slice.map((id) => seatButton(project, records[id], selectedSeatId)) })
|
||||
}
|
||||
return {
|
||||
type: 'stack',
|
||||
group: key,
|
||||
children: [{ type: 'text', text: GROUP_TITLE[key] + ' · ' + ids.length + ' 席' }].concat(rows),
|
||||
}
|
||||
}
|
||||
|
||||
/** 选中席详情:名称/职责/只读补充说明/模型单选/进入会话按钮。 */
|
||||
function selectedDetail(project, records, selectedSeatId, models) {
|
||||
const seat = selectedSeatId ? records[selectedSeatId] : null
|
||||
if (!seat) {
|
||||
return { type: 'callout', tone: 'info', text: '点击上方角色卡片查看职责、模型与进入会话。' }
|
||||
}
|
||||
const meta = SEATS[seat.id]
|
||||
const bound = isBound(seat)
|
||||
const statusLabel = SEAT_STATUS_TEXT[seat.status] || asText(seat.status) || '未知'
|
||||
const instructions = asText(seat.instructions).trim() || '(未填写)'
|
||||
return {
|
||||
type: 'stack',
|
||||
detail: seat.id,
|
||||
children: [
|
||||
{ type: 'text', text: meta.label + ' · ' + meta.duty + ' · ' + statusLabel },
|
||||
{ type: 'callout', tone: 'info', text: '职责:' + meta.responsibility },
|
||||
{ type: 'text', text: '角色补充说明(只读,请在 Web 端编辑)' },
|
||||
{ type: 'callout', tone: 'warn', text: instructions },
|
||||
buildModelSelect(project, seat, models),
|
||||
{
|
||||
type: 'button',
|
||||
label: bound ? '进入' + meta.label + '会话' : meta.label + '尚未绑定会话',
|
||||
variant: bound ? 'primary' : 'ghost',
|
||||
disabled: !bound,
|
||||
action: {
|
||||
type: 'sansheng/enter-session',
|
||||
seatId: seat.id,
|
||||
projectId: (project && project.id) || null,
|
||||
sessionId: isBound(seat) ? seat.sessionId : null,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造原生面板视图树。
|
||||
* @param {{ project: object|null, selectedSeatId?: string|null, models?: object|null }} input
|
||||
* @returns {object} 原生 view 节点
|
||||
*/
|
||||
export function buildPanelView(input) {
|
||||
const { project = null, selectedSeatId = null, models = null } = input || {}
|
||||
|
||||
if (!project || typeof project !== 'object') {
|
||||
return {
|
||||
type: 'stack',
|
||||
children: [
|
||||
{ type: 'text', text: '三省六部' },
|
||||
{
|
||||
type: 'callout',
|
||||
tone: 'warn',
|
||||
text: '无法确定当前项目:原生面板作用域不含 workspaceId,且未能由 sessionId 反查到所属项目。请从已启用「三省六部」的项目会话中打开,或在 Web 工作台查看。',
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
const records = seatRecords(project)
|
||||
// 选中席:显式传入优先;否则默认丞相(首屏有一个可见的选中态)。
|
||||
const sel = selectedSeatId && records[selectedSeatId] ? selectedSeatId : records.lead ? 'lead' : null
|
||||
const ready = project.status === 'ready'
|
||||
const boundCount = SEAT_IDS.filter((id) => isBound(records[id])).length
|
||||
|
||||
const children = [
|
||||
{ type: 'text', text: '三省六部 · ' + (asText(project.name) || '未命名项目') },
|
||||
{
|
||||
type: 'callout',
|
||||
tone: ready ? 'good' : 'warn',
|
||||
text: (PROJECT_STATUS_TEXT[project.status] || '状态未知') + ' · 已绑定 ' + boundCount + '/10 席',
|
||||
},
|
||||
]
|
||||
|
||||
for (const key of GROUP_ORDER) {
|
||||
const g = groupNode(project, records, key, sel)
|
||||
if (g) children.push(g)
|
||||
}
|
||||
|
||||
children.push(selectedDetail(project, records, sel, models))
|
||||
return { type: 'stack', children }
|
||||
}
|
||||
|
||||
export default buildPanelView
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
// 十席固定编制。id 与 preview 原型保持一致;显示名一律两字。
|
||||
// duty 为卡片短摘要;responsibility 为项目规划里从旧代码逐字沿用的职责说明。
|
||||
|
||||
export const SEAT_IDS = Object.freeze([
|
||||
'lead', 'zhongshu', 'shangshu', 'menxia',
|
||||
'libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu',
|
||||
])
|
||||
|
||||
export const SEATS = Object.freeze({
|
||||
lead: {
|
||||
id: 'lead', label: '丞相', duty: '接需求 · 协调汇报',
|
||||
responsibility: '面向用户承接想法:判断是否需要开工、必要时派给具体部门,并把各部门结果汇总成对用户的一次交付。',
|
||||
},
|
||||
zhongshu: {
|
||||
id: 'zhongshu', label: '中书', duty: '调查 · 澄清 · 规划',
|
||||
responsibility: '先把问题问清、把材料看全,再给出可执行的方案与验收标准草案,不直接产出最终交付物。',
|
||||
},
|
||||
shangshu: {
|
||||
id: 'shangshu', label: '尚书', duty: '分工 · 组织交付',
|
||||
responsibility: '把已经明确的方案拆成部门分工并组织交付;六部直属于尚书这一同级分组,六部之间不是上下级。',
|
||||
},
|
||||
menxia: {
|
||||
id: 'menxia', label: '门下', duty: '审议 · 整体审核',
|
||||
responsibility: '对方案和交付做独立审议,指出风险与不达标处。首版没有门下审核的任务必须如实标注“未审核”。',
|
||||
},
|
||||
libu: {
|
||||
id: 'libu', label: '吏部', duty: '角色 · 技能配置',
|
||||
responsibility: '对角色、技能与编制给出建议;职责不含绕过用户授权去改权限或其他项目设置。',
|
||||
},
|
||||
hubu: {
|
||||
id: 'hubu', label: '户部', duty: '数据 · 表格计算',
|
||||
responsibility: '处理数据、表格与计算,结论应可复算。',
|
||||
},
|
||||
lipu: {
|
||||
id: 'lipu', label: '礼部', duty: '文档 · 内容呈现',
|
||||
responsibility: '负责文档、内容与呈现形式,产出可编辑的源文件。',
|
||||
},
|
||||
bingbu: {
|
||||
id: 'bingbu', label: '兵部', duty: '环境 · 调试部署',
|
||||
responsibility: '负责环境、调试与部署;部署/发布等外部副作用仍服从用户授权与宿主审批。',
|
||||
},
|
||||
xingbu: {
|
||||
id: 'xingbu', label: '刑部', duty: '测试 · 风险检查',
|
||||
responsibility: '做测试与风险检查,给出可追溯的检查结果,而不是一句“已通过”。',
|
||||
},
|
||||
gongbu: {
|
||||
id: 'gongbu', label: '工部', duty: '代码 · 工程产出',
|
||||
responsibility: '负责代码实现与工程产出,交付可编辑源文件与真实检查结果。',
|
||||
},
|
||||
})
|
||||
|
||||
// 工作台布局:丞相居中;三省一排;六部两排。
|
||||
export const SEAT_GROUPS = Object.freeze({
|
||||
lead: Object.freeze(['lead']),
|
||||
sansheng: Object.freeze(['zhongshu', 'shangshu', 'menxia']),
|
||||
liubu: Object.freeze(['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu']),
|
||||
})
|
||||
|
||||
export function isSeatId(id) {
|
||||
return SEAT_IDS.includes(id)
|
||||
}
|
||||
|
||||
export function seatOf(id) {
|
||||
return SEATS[id]
|
||||
}
|
||||
|
||||
export function seatLabel(id) {
|
||||
return SEATS[id]?.label ?? ''
|
||||
}
|
||||
|
||||
/** 由 sessionId 反查所属席(用于 systemPrompt section 与项目归属校验)。 */
|
||||
export function seatBySessionId(projects, sessionId) {
|
||||
if (!sessionId || !projects) return undefined
|
||||
for (const project of Object.values(projects)) {
|
||||
for (const seatId of SEAT_IDS) {
|
||||
if (project?.seats?.[seatId]?.sessionId === sessionId) {
|
||||
return { project, seatId, seat: SEATS[seatId] }
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
|
@ -0,0 +1,101 @@
|
|||
// 项目状态 schema(版本 1)。前后端共用:宿主只接受明确合法的结构,
|
||||
// 合法 JSON 但结构错误一律视为损坏,绝不静默回退成“健康空状态”。
|
||||
import { SEAT_IDS } from './roles.js'
|
||||
|
||||
export const STATE_VERSION = 1
|
||||
|
||||
export const SEAT_STATUS = Object.freeze(['pending', 'creating', 'bound', 'failed', 'missing'])
|
||||
export const PROJECT_STATUS = Object.freeze(['pending', 'provisioning', 'ready', 'error'])
|
||||
|
||||
const SEAT_STATUS_SET = new Set(SEAT_STATUS)
|
||||
const PROJECT_STATUS_SET = new Set(PROJECT_STATUS)
|
||||
|
||||
function isObject(v) { return v !== null && typeof v === 'object' && !Array.isArray(v) }
|
||||
function isStr(v) { return typeof v === 'string' && v.trim() !== '' }
|
||||
|
||||
export function emptyState() {
|
||||
return { version: STATE_VERSION, seq: 0, projects: {} }
|
||||
}
|
||||
|
||||
export function emptySeat(seatId) {
|
||||
return {
|
||||
seatId,
|
||||
sessionId: null,
|
||||
plannedSessionId: null,
|
||||
status: 'pending',
|
||||
model: null,
|
||||
instructions: '',
|
||||
error: null,
|
||||
updatedAt: 0,
|
||||
}
|
||||
}
|
||||
|
||||
export function emptyProject({ id, name, workspaceId = null, path = null, now = Date.now() }) {
|
||||
const seats = {}
|
||||
for (const seatId of SEAT_IDS) seats[seatId] = emptySeat(seatId)
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
workspaceId,
|
||||
path,
|
||||
status: 'pending',
|
||||
seats,
|
||||
revision: 0,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}
|
||||
}
|
||||
|
||||
export function validModel(model) {
|
||||
if (model === null || model === undefined) return true
|
||||
if (!isObject(model)) return false
|
||||
if (!isStr(model.provider) || !isStr(model.model)) return false
|
||||
if (model.reasoningEffort !== undefined && typeof model.reasoningEffort !== 'string') return false
|
||||
return true
|
||||
}
|
||||
|
||||
function seatProblem(seat, seatId, projectId) {
|
||||
if (!isObject(seat)) return `项目 ${projectId} 的席 ${seatId} 不是对象`
|
||||
if (seat.seatId !== seatId) return `项目 ${projectId} 的席 ${seatId} 的 seatId 不一致`
|
||||
if (!SEAT_STATUS_SET.has(seat.status)) return `项目 ${projectId} 的席 ${seatId} 状态非法:${String(seat.status)}`
|
||||
for (const field of ['sessionId', 'plannedSessionId']) {
|
||||
if (!(seat[field] === null || isStr(seat[field]))) return `项目 ${projectId} 的席 ${seatId} 的 ${field} 非法`
|
||||
}
|
||||
if (!validModel(seat.model)) return `项目 ${projectId} 的席 ${seatId} 的 model 非法`
|
||||
if (typeof seat.instructions !== 'string') return `项目 ${projectId} 的席 ${seatId} 的 instructions 非法`
|
||||
if (!(seat.error === null || typeof seat.error === 'string')) return `项目 ${projectId} 的席 ${seatId} 的 error 非法`
|
||||
return undefined
|
||||
}
|
||||
|
||||
function projectProblem(project, id) {
|
||||
if (!isObject(project)) return `项目 ${id} 不是对象`
|
||||
if (!isStr(project.id)) return `项目 ${id} 缺少 id`
|
||||
if (project.id !== id) return `项目键 ${id} 与 id ${project.id} 不一致`
|
||||
if (typeof project.name !== 'string') return `项目 ${id} 的 name 非法`
|
||||
if (!PROJECT_STATUS_SET.has(project.status)) return `项目 ${id} 状态非法:${String(project.status)}`
|
||||
if (!(project.workspaceId === null || isStr(project.workspaceId))) return `项目 ${id} 的 workspaceId 非法`
|
||||
if (!(project.path === null || typeof project.path === 'string')) return `项目 ${id} 的 path 非法`
|
||||
if (!Number.isFinite(project.revision)) return `项目 ${id} 的 revision 非法`
|
||||
if (!isObject(project.seats)) return `项目 ${id} 缺少 seats`
|
||||
const keys = Object.keys(project.seats).sort()
|
||||
if (keys.length !== SEAT_IDS.length || keys.join(',') !== [...SEAT_IDS].sort().join(',')) {
|
||||
return `项目 ${id} 的席不是固定的十席`
|
||||
}
|
||||
for (const seatId of SEAT_IDS) {
|
||||
const problem = seatProblem(project.seats[seatId], seatId, id)
|
||||
if (problem) return problem
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function validateState(raw) {
|
||||
if (!isObject(raw)) return { ok: false, error: '状态顶层不是对象' }
|
||||
if (raw.version !== STATE_VERSION) return { ok: false, error: `不支持的状态版本 ${String(raw.version)}` }
|
||||
if (!isObject(raw.projects)) return { ok: false, error: 'projects 不是对象' }
|
||||
if (raw.seq !== undefined && !Number.isFinite(raw.seq)) return { ok: false, error: 'seq 不是数字' }
|
||||
for (const [id, project] of Object.entries(raw.projects)) {
|
||||
const problem = projectProblem(project, id)
|
||||
if (problem) return { ok: false, error: problem }
|
||||
}
|
||||
return { ok: true, state: raw }
|
||||
}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { createApiHandler } from '../src/host/api.js'
|
||||
import { setupService } from './helpers.js'
|
||||
|
||||
test('HTTP 处理器端到端', async () => {
|
||||
const { service } = await setupService()
|
||||
const handle = createApiHandler(service)
|
||||
|
||||
let r = await handle('list')
|
||||
assert.ok(r.ok)
|
||||
assert.deepEqual(r.value.projects, [])
|
||||
|
||||
r = await handle('open', { path: '/api', name: '接口项目' })
|
||||
assert.ok(r.ok)
|
||||
const id = r.value.project.id
|
||||
|
||||
r = await handle('enable', { projectId: id })
|
||||
assert.ok(r.ok)
|
||||
assert.equal(r.value.project.status, 'ready')
|
||||
|
||||
r = await handle('configure', { projectId: id, seatId: 'gongbu', model: { provider: 'deepseek', model: 'deepseek-chat' }, instructions: '说明' })
|
||||
assert.ok(r.ok)
|
||||
assert.deepEqual(r.value.seat.model, { provider: 'deepseek', model: 'deepseek-chat' })
|
||||
|
||||
r = await handle('project', { projectId: id })
|
||||
assert.ok(r.ok)
|
||||
assert.equal(r.value.project.seats.length, 10)
|
||||
|
||||
r = await handle('models')
|
||||
assert.ok(r.ok)
|
||||
assert.ok(r.value.providers.length >= 1)
|
||||
|
||||
r = await handle('nope')
|
||||
assert.ok(!r.ok)
|
||||
assert.equal(r.error.code, 'sansheng/invalid')
|
||||
|
||||
r = await handle('project', {})
|
||||
assert.ok(!r.ok)
|
||||
|
||||
r = await handle('project', { projectId: 'missing' })
|
||||
assert.ok(!r.ok)
|
||||
assert.equal(r.error.code, 'sansheng/not-found')
|
||||
})
|
||||
|
|
@ -0,0 +1,141 @@
|
|||
// 只测纯视图模型:绝不 import 会拉起 React 的 index.js。
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {
|
||||
buildWorkbenchView,
|
||||
collectModelOptions,
|
||||
updateDraft,
|
||||
UNCHOSEN_MODEL_LABEL,
|
||||
} from '../src/client/workbench.js'
|
||||
|
||||
// 与 CONTRACT.md 一致:十席固定编制、两字显示名。
|
||||
const SEAT_ROWS = [
|
||||
['lead', '丞相'],
|
||||
['zhongshu', '中书'],
|
||||
['shangshu', '尚书'],
|
||||
['menxia', '门下'],
|
||||
['libu', '吏部'],
|
||||
['hubu', '户部'],
|
||||
['lipu', '礼部'],
|
||||
['bingbu', '兵部'],
|
||||
['xingbu', '刑部'],
|
||||
['gongbu', '工部'],
|
||||
]
|
||||
|
||||
const GROUPS = {
|
||||
lead: ['lead'],
|
||||
sansheng: ['zhongshu', 'shangshu', 'menxia'],
|
||||
liubu: ['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu'],
|
||||
}
|
||||
|
||||
const MODELS = {
|
||||
providers: [
|
||||
{
|
||||
provider: 'deepseek',
|
||||
models: [
|
||||
{ model: 'deepseek-chat' },
|
||||
{ model: 'deepseek-reasoner', reasoningEffort: ['low', 'high'] },
|
||||
],
|
||||
},
|
||||
],
|
||||
default: { provider: 'deepseek', model: 'deepseek-chat' },
|
||||
failures: [],
|
||||
}
|
||||
|
||||
function makeView(seatPatch, projectPatch) {
|
||||
const seats = SEAT_ROWS.map(pair => {
|
||||
const id = pair[0]
|
||||
const patch = (seatPatch && seatPatch[id]) || {}
|
||||
return {
|
||||
id,
|
||||
label: '',
|
||||
duty: '',
|
||||
responsibility: '',
|
||||
status: 'pending',
|
||||
sessionId: null,
|
||||
model: null,
|
||||
instructions: '',
|
||||
...patch,
|
||||
}
|
||||
})
|
||||
return {
|
||||
revision: 1,
|
||||
project: {
|
||||
id: 'ws-1',
|
||||
name: '测试项目',
|
||||
workspaceId: 'ws-1',
|
||||
path: 'D:/x',
|
||||
status: 'ready',
|
||||
seats,
|
||||
groups: GROUPS,
|
||||
...(projectPatch || {}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
test('十席固定编制,名称均为两字', () => {
|
||||
const out = buildWorkbenchView(makeView(), { selectedSeatId: 'lead', models: MODELS, draft: {} })
|
||||
assert.equal(out.seats.length, 10)
|
||||
assert.deepEqual(out.seats.map(s => s.id), SEAT_ROWS.map(r => r[0]))
|
||||
for (const seat of out.seats) {
|
||||
assert.equal(Array.from(seat.name).length, 2, seat.id + ' 的名称应为两字,实际 ' + seat.name)
|
||||
}
|
||||
// 缺省入参也不应抛错,且仍是十席。
|
||||
const bare = buildWorkbenchView(undefined, undefined)
|
||||
assert.equal(bare.seats.length, 10)
|
||||
})
|
||||
|
||||
test('groups 键与分组归属正确', () => {
|
||||
const out = buildWorkbenchView(makeView(), { selectedSeatId: 'shangshu', models: MODELS, draft: {} })
|
||||
assert.deepEqual(Object.keys(out.groups).sort(), ['lead', 'liubu', 'sansheng'])
|
||||
assert.deepEqual(out.groups.lead, ['lead'])
|
||||
assert.deepEqual(out.groups.sansheng, ['zhongshu', 'shangshu', 'menxia'])
|
||||
assert.deepEqual(out.groups.liubu, ['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu'])
|
||||
})
|
||||
|
||||
test('未选模型时显示“请选择模型”,且 modelOptions 无 inherit 选项', () => {
|
||||
const out = buildWorkbenchView(makeView(), { selectedSeatId: 'lead', models: MODELS, draft: {} })
|
||||
assert.equal(out.selected.modelLabel, UNCHOSEN_MODEL_LABEL)
|
||||
assert.equal(out.selected.modelLabel, '请选择模型')
|
||||
assert.equal(out.selected.modelValue, '')
|
||||
assert.ok(Array.isArray(out.selected.modelOptions))
|
||||
assert.ok(out.selected.modelOptions.length > 0)
|
||||
assert.ok(!out.selected.modelOptions.some(o => o.value === 'inherit'))
|
||||
assert.ok(!out.selected.modelOptions.some(o => o.value === 'inherit'))
|
||||
// 顶层也再次覆核,防止某处泄漏“跟随宿主模型”。
|
||||
assert.ok(!collectModelOptions(MODELS).some(o => o.value === 'inherit'))
|
||||
})
|
||||
|
||||
test('选中模型后显示具体名称', () => {
|
||||
const view = makeView({ lead: { model: { provider: 'deepseek', model: 'deepseek-chat' }, status: 'bound', sessionId: 'sess-lead' } })
|
||||
const out = buildWorkbenchView(view, { selectedSeatId: 'lead', models: MODELS, draft: {} })
|
||||
assert.equal(out.selected.modelLabel, 'deepseek-chat')
|
||||
assert.equal(out.selected.modelValue, 'deepseek::deepseek-chat')
|
||||
assert.equal(out.selected.sessionId, 'sess-lead')
|
||||
assert.equal(out.selected.name, '丞相')
|
||||
// selected 必须带齐契约要求的字段。
|
||||
for (const key of ['id', 'name', 'responsibility', 'duty', 'modelValue', 'modelLabel', 'instructions', 'modelOptions']) {
|
||||
assert.ok(key in out.selected, 'selected 缺少字段 ' + key)
|
||||
}
|
||||
})
|
||||
|
||||
test('切换角色保留草稿', () => {
|
||||
// 工部写一句草稿,再切到吏部写一句:两席草稿互不覆盖。
|
||||
let draft = updateDraft({}, 'gongbu', { instructions: '工部草稿' })
|
||||
draft = updateDraft(draft, 'libu', { instructions: '吏部草稿' })
|
||||
assert.equal(draft.gongbu.instructions, '工部草稿')
|
||||
assert.equal(draft.libu.instructions, '吏部草稿')
|
||||
|
||||
const view = makeView()
|
||||
const gongbuView = buildWorkbenchView(view, { selectedSeatId: 'gongbu', models: MODELS, draft })
|
||||
assert.equal(gongbuView.selected.id, 'gongbu')
|
||||
assert.equal(gongbuView.selected.instructions, '工部草稿')
|
||||
assert.equal(gongbuView.selected.dirty, true)
|
||||
|
||||
// 切到吏部——工部草稿仍在 draft 映射里,切回工部应原样保留。
|
||||
const libuView = buildWorkbenchView(view, { selectedSeatId: 'libu', models: MODELS, draft })
|
||||
assert.equal(libuView.selected.instructions, '吏部草稿')
|
||||
|
||||
const again = buildWorkbenchView(view, { selectedSeatId: 'gongbu', models: MODELS, draft })
|
||||
assert.equal(again.selected.instructions, '工部草稿')
|
||||
})
|
||||
|
|
@ -0,0 +1,106 @@
|
|||
// 测试用 fake 宿主:模拟 DSH 注入的公开服务,便于隔离验证,不接触真实 DSH。
|
||||
import { mkdtemp } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
export async function tempStateFile() {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-test-'))
|
||||
return join(dir, 'state.json')
|
||||
}
|
||||
|
||||
export function createFakeHost(opts = {}) {
|
||||
const sessions = new Map() // sessionId -> agent
|
||||
const workspaces = new Map() // id -> { id, name, path }
|
||||
const calls = { create: [], resolve: [], selectModel: 0, agentSelect: [], createAt: [] }
|
||||
const control = {
|
||||
failCreateOrder: null, // 第 N 次 create 抛错(1 起)
|
||||
mismatchCreateOrder: null, // 第 N 次 create 返回另一个 ID
|
||||
catalog: opts.catalog ?? {
|
||||
providers: [{ provider: 'deepseek', models: ['deepseek-chat', 'deepseek-reasoner'] }],
|
||||
default: { provider: 'deepseek', model: 'deepseek-chat' },
|
||||
failures: [],
|
||||
},
|
||||
validRoutes: opts.validRoutes ?? new Set(['deepseek/deepseek-chat', 'deepseek/deepseek-reasoner']),
|
||||
}
|
||||
let createCount = 0
|
||||
|
||||
const workspaceRegistry = {
|
||||
get(id) { return workspaces.get(id) },
|
||||
list() { return [...workspaces.values()] },
|
||||
async resolveByPath(p) { return [...workspaces.values()].find(w => w.path === p) },
|
||||
async create(p, title) { const id = `ws-${workspaces.size + 1}`; const w = { id, name: title ?? id, path: p }; workspaces.set(id, w); return w },
|
||||
}
|
||||
|
||||
function agentFor(sessionId) {
|
||||
let agent = sessions.get(sessionId)
|
||||
if (!agent) {
|
||||
agent = {
|
||||
id: sessionId,
|
||||
_selection: null,
|
||||
model: {
|
||||
current() { return agent._selection },
|
||||
select(selection) { agent._selection = selection; calls.agentSelect.push({ sessionId, selection }) },
|
||||
},
|
||||
}
|
||||
sessions.set(sessionId, agent)
|
||||
}
|
||||
return agent
|
||||
}
|
||||
|
||||
const sessionController = {
|
||||
async resolveAgent(sessionId) {
|
||||
calls.resolve.push(sessionId)
|
||||
if (sessions.has(sessionId)) return { agent: sessions.get(sessionId) }
|
||||
return { error: { code: 'session/not-found', message: 'session not found' } }
|
||||
},
|
||||
async create({ sessionId, workspaceId, cwd } = {}) {
|
||||
createCount += 1
|
||||
const order = createCount
|
||||
calls.create.push({ sessionId, workspaceId, cwd, order })
|
||||
if (control.failCreateOrder === order) {
|
||||
const error = new Error('simulated create failure')
|
||||
error.code = 'session/create-failed'
|
||||
throw error
|
||||
}
|
||||
let actual = sessionId
|
||||
if (control.mismatchCreateOrder === order) actual = `minted-${Math.random().toString(36).slice(2, 8)}`
|
||||
agentFor(actual)
|
||||
return { sessionId: actual }
|
||||
},
|
||||
async modelCatalog() { return control.catalog },
|
||||
// 我们的代码绝不能调用它(会写 profile 全局默认);被调用即失败并计数。
|
||||
async selectModel() { calls.selectModel += 1; throw new Error('sessionController.selectModel must not be called') },
|
||||
}
|
||||
|
||||
const agents = { get(id) { return sessions.get(id) }, list() { return [...sessions.values()] } }
|
||||
const llm = {
|
||||
async resolveCallConfig(selection) {
|
||||
const key = `${selection.provider}/${selection.model}`
|
||||
if (control.validRoutes.size > 0 && !control.validRoutes.has(key)) {
|
||||
const error = new Error(`unknown route ${key}`)
|
||||
error.code = 'llm/unknown-model'
|
||||
throw error
|
||||
}
|
||||
return { ...selection }
|
||||
},
|
||||
}
|
||||
let promptSection = null
|
||||
const systemPrompt = { section(def) { promptSection = def; return () => { promptSection = null } } }
|
||||
let route = null
|
||||
const connection = { fetch: { register(def) { route = def; return () => {} } } }
|
||||
|
||||
const host = { workspaceRegistry, sessionController, agents, llm, systemPrompt }
|
||||
const ctx = {
|
||||
workspaceRegistry, sessionController, agents, llm, systemPrompt, connection,
|
||||
effect(fn) { const dispose = fn(); return dispose },
|
||||
}
|
||||
|
||||
return {
|
||||
host, ctx, calls, control, sessions, workspaces,
|
||||
getPromptSection() { return promptSection },
|
||||
getRoute() { return route },
|
||||
addWorkspace(id, name, path) { workspaces.set(id, { id, name, path }) },
|
||||
// 预置一个已存在的会话(用于“已存在不重建”测试)
|
||||
addSession(sessionId) { return agentFor(sessionId) },
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import { SanshengStore } from '../src/host/store.js'
|
||||
import { createProvisioner } from '../src/host/provision.js'
|
||||
import { SanshengService } from '../src/host/service.js'
|
||||
import { createFakeHost, tempStateFile } from './fake-ctx.js'
|
||||
|
||||
export async function setupService(opts = {}) {
|
||||
const file = await tempStateFile()
|
||||
const store = new SanshengStore(file)
|
||||
await store.load()
|
||||
const fake = opts.fake ?? createFakeHost(opts)
|
||||
const provisioner = createProvisioner({ store, host: fake.host })
|
||||
const service = new SanshengService({ store, host: fake.host, provisioner })
|
||||
return { file, store, fake, provisioner, service }
|
||||
}
|
||||
|
||||
export function seatById(view, id) {
|
||||
return view.project.seats.find(s => s.id === id)
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { setupService } from './helpers.js'
|
||||
import { buildWorkbenchView } from '../src/client/workbench.js'
|
||||
import { buildPanelView } from '../src/native/panel.js'
|
||||
|
||||
function childNodes(node) {
|
||||
const kids = node?.children ?? node?.items ?? []
|
||||
return Array.isArray(kids) ? kids : []
|
||||
}
|
||||
function countNodes(node) {
|
||||
if (!node || typeof node !== 'object') return 0
|
||||
let total = 1
|
||||
for (const child of childNodes(node)) total += countNodes(child)
|
||||
return total
|
||||
}
|
||||
function depth(node) {
|
||||
if (!node || typeof node !== 'object') return 0
|
||||
let max = 0
|
||||
for (const child of childNodes(node)) max = Math.max(max, depth(child))
|
||||
return 1 + max
|
||||
}
|
||||
|
||||
test('宿主项目视图可直接喂给 Web 纯视图模型', async () => {
|
||||
const { service } = await setupService()
|
||||
const opened = await service.open({ path: '/ui', name: '界面项目' })
|
||||
await service.enable(opened.project.id)
|
||||
await service.configure(opened.project.id, 'gongbu', { model: { provider: 'deepseek', model: 'deepseek-chat' } })
|
||||
|
||||
const view = await service.project(opened.project.id)
|
||||
const models = await service.models()
|
||||
const vm = buildWorkbenchView(view, { selectedSeatId: 'gongbu', models })
|
||||
|
||||
assert.equal(vm.seats.length, 10)
|
||||
assert.ok(vm.seats.every(s => s.name.length === 2))
|
||||
assert.deepEqual(vm.groups, { lead: ['lead'], sansheng: ['zhongshu', 'shangshu', 'menxia'], liubu: ['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu'] })
|
||||
assert.equal(vm.ready, true)
|
||||
assert.equal(vm.selected.id, 'gongbu')
|
||||
assert.match(vm.selected.modelLabel, /deepseek-chat/)
|
||||
assert.ok(!vm.selected.modelOptions.some(o => o.value === 'inherit'))
|
||||
})
|
||||
|
||||
test('宿主项目视图可直接喂给原生面板并满足容量约束', async () => {
|
||||
const { service } = await setupService()
|
||||
const opened = await service.open({ path: '/ui2', name: '原生项目' })
|
||||
await service.enable(opened.project.id)
|
||||
const view = await service.project(opened.project.id)
|
||||
const models = await service.models()
|
||||
const tree = buildPanelView({ project: view.project, selectedSeatId: 'lead', models })
|
||||
assert.ok(countNodes(tree) <= 120, '节点数应 ≤120')
|
||||
assert.ok(depth(tree) <= 8, '深度应 ≤8')
|
||||
})
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { SanshengStore } from '../src/host/store.js'
|
||||
import { createProvisioner } from '../src/host/provision.js'
|
||||
import { SanshengService } from '../src/host/service.js'
|
||||
import { createFakeHost } from './fake-ctx.js'
|
||||
import { setupService, seatById } from './helpers.js'
|
||||
|
||||
test('两个项目十席会话与模型互相隔离', async () => {
|
||||
const { service, fake } = await setupService()
|
||||
const a = await service.open({ path: '/A', name: '甲项目' })
|
||||
const b = await service.open({ path: '/B', name: '乙项目' })
|
||||
await service.enable(a.project.id)
|
||||
await service.enable(b.project.id)
|
||||
|
||||
await service.configure(a.project.id, 'gongbu', { model: { provider: 'deepseek', model: 'deepseek-chat' } })
|
||||
await service.configure(b.project.id, 'gongbu', { model: { provider: 'deepseek', model: 'deepseek-reasoner' } })
|
||||
|
||||
const pa = await service.project(a.project.id)
|
||||
const pb = await service.project(b.project.id)
|
||||
assert.deepEqual(seatById(pa, 'gongbu').model, { provider: 'deepseek', model: 'deepseek-chat' })
|
||||
assert.deepEqual(seatById(pb, 'gongbu').model, { provider: 'deepseek', model: 'deepseek-reasoner' })
|
||||
|
||||
// 两会话 ID 集合不相交
|
||||
const sa = new Set(pa.project.seats.map(s => s.sessionId))
|
||||
for (const seat of pb.project.seats) assert.ok(!sa.has(seat.sessionId))
|
||||
})
|
||||
|
||||
test('重启后十席不重复,配置与会话保持不变', async () => {
|
||||
const { service, store, fake, file } = await setupService()
|
||||
const a = await service.open({ path: '/A', name: '甲项目' })
|
||||
await service.enable(a.project.id)
|
||||
await service.configure(a.project.id, 'gongbu', { model: { provider: 'deepseek', model: 'deepseek-reasoner' } })
|
||||
const before = await service.project(a.project.id)
|
||||
const sessionsBefore = before.project.seats.map(s => s.sessionId)
|
||||
|
||||
// 模拟重启:新 store + 新 service 读同一文件、同一 fake 宿主
|
||||
const store2 = new SanshengStore(file)
|
||||
await store2.load()
|
||||
const provisioner2 = createProvisioner({ store: store2, host: fake.host })
|
||||
const service2 = new SanshengService({ store: store2, host: fake.host, provisioner: provisioner2 })
|
||||
const createdBefore = fake.calls.create.length
|
||||
const again = await service2.enable(a.project.id) // 再次启用不应重建
|
||||
assert.equal(fake.calls.create.length, createdBefore, '重启后不得重复创建会话')
|
||||
assert.equal(again.project.seats.map(s => s.sessionId).join(','), sessionsBefore.join(','))
|
||||
assert.deepEqual(seatById(again, 'gongbu').model, { provider: 'deepseek', model: 'deepseek-reasoner' })
|
||||
})
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { setupService, seatById } from './helpers.js'
|
||||
|
||||
async function ready() {
|
||||
const ctx = await setupService()
|
||||
const opened = await ctx.service.open({ path: '/pm', name: '模型项目' })
|
||||
const id = opened.project.id
|
||||
await ctx.service.enable(id)
|
||||
return { ...ctx, id }
|
||||
}
|
||||
|
||||
test('配置模型走 agent.model.select,不调用 controller.selectModel', async () => {
|
||||
const { service, fake, id } = await ready()
|
||||
const res = await service.configure(id, 'gongbu', { model: { provider: 'deepseek', model: 'deepseek-chat' } })
|
||||
assert.equal(fake.calls.selectModel, 0)
|
||||
assert.equal(fake.calls.agentSelect.length, 1)
|
||||
assert.deepEqual(res.seat.model, { provider: 'deepseek', model: 'deepseek-chat' })
|
||||
const p = await service.project(id)
|
||||
assert.deepEqual(seatById(p, 'gongbu').model, { provider: 'deepseek', model: 'deepseek-chat' })
|
||||
})
|
||||
|
||||
test('非法模型被 validate 拒绝且不落库', async () => {
|
||||
const { service, fake, id } = await ready()
|
||||
await assert.rejects(
|
||||
() => service.configure(id, 'hubu', { model: { provider: 'ghost', model: 'nope' } }),
|
||||
err => err.code === 'sansheng/model-invalid' || err.code === 'llm/unknown-model',
|
||||
)
|
||||
assert.equal(fake.calls.agentSelect.length, 0)
|
||||
const p = await service.project(id)
|
||||
assert.equal(seatById(p, 'hubu').model, null)
|
||||
})
|
||||
|
||||
test('缺 provider/model 直接拒绝', async () => {
|
||||
const { service, id } = await ready()
|
||||
await assert.rejects(() => service.configure(id, 'libu', { model: { provider: 'deepseek' } }), err => err.code === 'sansheng/model-invalid')
|
||||
})
|
||||
|
||||
test('补充说明可保存并持久化', async () => {
|
||||
const { service, store, id } = await ready()
|
||||
await service.configure(id, 'xingbu', { instructions: '只跑只读检查' })
|
||||
const p = await service.project(id)
|
||||
assert.equal(seatById(p, 'xingbu').instructions, '只跑只读检查')
|
||||
})
|
||||
|
|
@ -0,0 +1,192 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { buildPanelView } from '../src/native/panel.js'
|
||||
import { SEATS, SEAT_GROUPS } from '../src/shared/roles.js'
|
||||
|
||||
/** 递归遍历视图树(沿 children),depth 从 1 起。 */
|
||||
function traverse(node, fn, depth = 1) {
|
||||
if (!node || typeof node !== 'object') return
|
||||
fn(node, depth)
|
||||
const kids = Array.isArray(node.children) ? node.children : []
|
||||
for (const k of kids) traverse(k, fn, depth + 1)
|
||||
}
|
||||
|
||||
function analyze(root) {
|
||||
let count = 0
|
||||
let maxDepth = 0
|
||||
let maxOptions = 0
|
||||
let maxItems = 0
|
||||
const types = new Set()
|
||||
const seatNodes = []
|
||||
traverse(root, (n, d) => {
|
||||
count += 1
|
||||
if (d > maxDepth) maxDepth = d
|
||||
if (typeof n.type === 'string') types.add(n.type)
|
||||
if (Array.isArray(n.options)) maxOptions = Math.max(maxOptions, n.options.length)
|
||||
if (Array.isArray(n.items)) maxItems = Math.max(maxItems, n.items.length)
|
||||
if (typeof n.seatId === 'string') seatNodes.push(n)
|
||||
})
|
||||
return { count, maxDepth, maxOptions, maxItems, types, seatNodes }
|
||||
}
|
||||
|
||||
function makeProject() {
|
||||
const seats = Object.keys(SEATS).map((id) => ({
|
||||
id,
|
||||
label: SEATS[id].label,
|
||||
duty: SEATS[id].duty,
|
||||
responsibility: SEATS[id].responsibility,
|
||||
status: 'bound',
|
||||
sessionId: 'sess-' + id,
|
||||
model: id === 'gongbu' ? { provider: 'demo', model: 'deepseek-chat' } : null,
|
||||
instructions: id === 'lead' ? '优先用中文,先给结论。' : '',
|
||||
}))
|
||||
return {
|
||||
id: 'p1',
|
||||
name: '演示项目',
|
||||
workspaceId: 'ws-1',
|
||||
path: 'D:/demo',
|
||||
status: 'ready',
|
||||
seats,
|
||||
groups: SEAT_GROUPS,
|
||||
}
|
||||
}
|
||||
|
||||
const MODELS = {
|
||||
providers: [
|
||||
{ provider: 'demo', models: [{ model: 'deepseek-chat' }, { model: 'deepseek-reasoner' }] },
|
||||
],
|
||||
default: { provider: 'demo', model: 'deepseek-chat' },
|
||||
failures: [],
|
||||
}
|
||||
|
||||
function build(extra) {
|
||||
return buildPanelView(Object.assign({ project: makeProject(), selectedSeatId: 'gongbu', models: MODELS }, extra || {}))
|
||||
}
|
||||
|
||||
test('十席:恰好十席、名称两字、分组齐全', () => {
|
||||
const view = build()
|
||||
const m = analyze(view)
|
||||
|
||||
// 恰好十席(唯一 seatId 的按钮节点)
|
||||
const ids = m.seatNodes.map((n) => n.seatId)
|
||||
assert.equal(ids.length, 10, '十席按钮应为 10 个')
|
||||
assert.equal(new Set(ids).size, 10, '十席 seatId 应互不相同')
|
||||
assert.deepEqual([...ids].sort(), Object.keys(SEATS).sort(), '应覆盖固定十席')
|
||||
|
||||
// 名称两字,且与共享定义一致
|
||||
for (const n of m.seatNodes) {
|
||||
assert.equal(Array.from(n.label).length, 2, n.seatId + ' 的名称应为两字:' + n.label)
|
||||
assert.equal(n.label, SEATS[n.seatId].label)
|
||||
}
|
||||
|
||||
// 分组齐全:lead / sansheng / liubu
|
||||
const groups = []
|
||||
traverse(view, (n) => { if (typeof n.group === 'string') groups.push(n.group) })
|
||||
assert.deepEqual(groups.sort(), ['lead', 'liubu', 'sansheng'].sort(), '应包含三个分组')
|
||||
|
||||
// 各分组席数:1 / 3 / 6
|
||||
const countInGroup = (groupKey) => {
|
||||
let groupNode = null
|
||||
traverse(view, (n) => { if (n.group === groupKey) groupNode = n })
|
||||
assert.ok(groupNode, '缺少分组 ' + groupKey)
|
||||
let c = 0
|
||||
traverse(groupNode, (n) => { if (typeof n.seatId === 'string') c += 1 })
|
||||
return c
|
||||
}
|
||||
assert.equal(countInGroup('lead'), 1)
|
||||
assert.equal(countInGroup('sansheng'), 3)
|
||||
assert.equal(countInGroup('liubu'), 6)
|
||||
// 分组定义一致性
|
||||
assert.equal(SEAT_GROUPS.liubu.length, 6)
|
||||
})
|
||||
|
||||
test('容量:节点 ≤120、深度 ≤8、options/items ≤8', () => {
|
||||
const m = analyze(build())
|
||||
assert.ok(m.count <= 120, '节点数应 ≤120,实际 ' + m.count)
|
||||
assert.ok(m.maxDepth <= 8, '最大深度应 ≤8,实际 ' + m.maxDepth)
|
||||
assert.ok(m.maxOptions <= 8, 'options 项数应 ≤8,实际 ' + m.maxOptions)
|
||||
assert.ok(m.maxItems <= 8, 'items 项数应 ≤8,实际 ' + m.maxItems)
|
||||
})
|
||||
|
||||
test('模型为原生单选且不超过 8 项,含“请选择模型”占位', () => {
|
||||
const view = build()
|
||||
let select = null
|
||||
traverse(view, (n) => { if (n.type === 'select') select = n })
|
||||
assert.ok(select, '应存在模型单选节点')
|
||||
assert.ok(Array.isArray(select.options))
|
||||
assert.ok(select.options.length <= 8)
|
||||
assert.equal(select.options[0].value, '')
|
||||
assert.equal(select.options[0].label, '请选择模型')
|
||||
// 已选中的工部模型应回填为具体 provider::model
|
||||
assert.equal(select.value, 'demo::deepseek-chat')
|
||||
|
||||
// 即使喂入大量模型候选,也要被截断到 ≤8(含占位)
|
||||
const many = { providers: [{ provider: 'p', models: Array.from({ length: 20 }, (_, i) => ({ model: 'm' + i })) }] }
|
||||
const bigView = buildPanelView({ project: makeProject(), selectedSeatId: 'gongbu', models: many })
|
||||
let bigSelect = null
|
||||
traverse(bigView, (n) => { if (n.type === 'select') bigSelect = n })
|
||||
assert.ok(bigSelect.options.length <= 8, '模型候选应被截断到 ≤8 项')
|
||||
})
|
||||
|
||||
test('不存在自由文本输入控件(input/textarea)', () => {
|
||||
const view = build()
|
||||
const bad = []
|
||||
traverse(view, (n) => {
|
||||
if (n.type === 'input' || n.type === 'textarea') bad.push(n.type)
|
||||
if (typeof n.component === 'string' && (n.component === 'input' || n.component === 'textarea')) bad.push(n.component)
|
||||
})
|
||||
assert.deepEqual(bad, [], '不应出现自由文本控件:' + bad.join(','))
|
||||
// 同时确认渲染出的类型集合里没有意外控件
|
||||
const m = analyze(view)
|
||||
assert.ok(!m.types.has('input'))
|
||||
assert.ok(!m.types.has('textarea'))
|
||||
})
|
||||
|
||||
test('选中席出现在树里并高亮', () => {
|
||||
const view = build({ selectedSeatId: 'bingbu' })
|
||||
const m = analyze(view)
|
||||
const hit = m.seatNodes.find((n) => n.seatId === 'bingbu')
|
||||
assert.ok(hit, '选中的兵部应出现在树中')
|
||||
assert.equal(hit.selected, true, '选中席应标记 selected=true')
|
||||
assert.equal(hit.variant, 'primary', '选中席应高亮(primary)')
|
||||
// 其它席不应被标记选中
|
||||
const others = m.seatNodes.filter((n) => n.seatId !== 'bingbu')
|
||||
assert.ok(others.every((n) => n.selected !== true), '非选中席不应高亮')
|
||||
// 详情区应出现选中席名称(两字名)
|
||||
let hasName = false
|
||||
traverse(view, (n) => { if (n.type === 'text' && typeof n.text === 'string' && n.text.includes(SEATS.bingbu.label)) hasName = true })
|
||||
assert.ok(hasName, '详情区应包含选中席名称')
|
||||
})
|
||||
|
||||
test('进入会话按钮:表达意图(含 seatId/sessionId),未绑定则禁用', () => {
|
||||
const view = build({ selectedSeatId: 'hubu' })
|
||||
let enter = null
|
||||
traverse(view, (n) => {
|
||||
if (n.type === 'button' && n.action && n.action.type === 'sansheng/enter-session') enter = n
|
||||
})
|
||||
assert.ok(enter, '应存在进入会话按钮')
|
||||
assert.equal(enter.action.seatId, 'hubu')
|
||||
assert.equal(enter.action.sessionId, 'sess-hubu')
|
||||
assert.equal(enter.disabled, false)
|
||||
|
||||
// 未绑定席:按钮禁用
|
||||
const project = makeProject()
|
||||
const hubu = project.seats.find((s) => s.id === 'hubu')
|
||||
hubu.sessionId = null
|
||||
hubu.status = 'pending'
|
||||
const view2 = buildPanelView({ project, selectedSeatId: 'hubu', models: MODELS })
|
||||
let enter2 = null
|
||||
traverse(view2, (n) => {
|
||||
if (n.type === 'button' && n.action && n.action.type === 'sansheng/enter-session') enter2 = n
|
||||
})
|
||||
assert.equal(enter2.disabled, true, '未绑定席的进入会话按钮应禁用')
|
||||
})
|
||||
|
||||
test('缺少项目时给出安全提示(scope 无 workspaceId 的兜底)', () => {
|
||||
const view = buildPanelView({ project: null, selectedSeatId: null, models: null })
|
||||
let shown = false
|
||||
traverse(view, (n) => { if (n.type === 'callout' && typeof n.text === 'string' && n.text.includes('无法确定当前项目')) shown = true })
|
||||
assert.ok(shown, '无项目时应显示安全提示')
|
||||
const m = analyze(view)
|
||||
assert.ok(m.count <= 120 && m.maxDepth <= 8)
|
||||
})
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { installPromptSection } from '../src/host/prompt.js'
|
||||
import { setupService, seatById } from './helpers.js'
|
||||
|
||||
test('只对十席会话注入角色提示', async () => {
|
||||
const { service, store, fake } = await setupService()
|
||||
installPromptSection(fake.ctx, { store })
|
||||
const section = fake.getPromptSection()
|
||||
assert.ok(section)
|
||||
assert.equal(section.name, 'sansheng')
|
||||
|
||||
const opened = await service.open({ path: '/pp', name: '提示项目' })
|
||||
await service.enable(opened.project.id)
|
||||
const p = await service.project(opened.project.id)
|
||||
const seat = seatById(p, 'gongbu')
|
||||
|
||||
const text = section.text({ agent: { id: seat.sessionId } })
|
||||
assert.match(text, /工部/)
|
||||
assert.match(text, /代码实现与工程产出/)
|
||||
|
||||
assert.equal(section.text({ agent: { id: 'other-session' } }), '')
|
||||
assert.equal(section.text({}), '')
|
||||
})
|
||||
|
||||
test('补充说明出现在提示里', async () => {
|
||||
const { service, store, fake } = await setupService()
|
||||
installPromptSection(fake.ctx, { store })
|
||||
const opened = await service.open({ path: '/pp2', name: 'p' })
|
||||
await service.enable(opened.project.id)
|
||||
await service.configure(opened.project.id, 'libu', { instructions: '先问清目标' })
|
||||
const p = await service.project(opened.project.id)
|
||||
const text = fake.getPromptSection().text({ agent: { id: seatById(p, 'libu').sessionId } })
|
||||
assert.match(text, /先问清目标/)
|
||||
})
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { SEAT_IDS } from '../src/shared/roles.js'
|
||||
import { setupService, seatById } from './helpers.js'
|
||||
|
||||
test('启用创建十席并全部绑定', async () => {
|
||||
const { service, fake } = await setupService()
|
||||
const opened = await service.open({ path: '/p1', name: '项目一' })
|
||||
const id = opened.project.id
|
||||
assert.equal(opened.project.seats.length, 10)
|
||||
const enabled = await service.enable(id)
|
||||
assert.equal(enabled.project.status, 'ready')
|
||||
assert.equal(fake.calls.create.length, 10)
|
||||
for (const seat of enabled.project.seats) {
|
||||
assert.equal(seat.status, 'bound')
|
||||
assert.ok(seat.sessionId)
|
||||
}
|
||||
assert.equal(new Set(enabled.project.seats.map(s => s.sessionId)).size, 10)
|
||||
assert.equal(fake.calls.selectModel, 0)
|
||||
})
|
||||
|
||||
test('已存在会话不重建(按既有会话恢复绑定)', async () => {
|
||||
const { service, store, fake } = await setupService()
|
||||
const opened = await service.open({ path: '/p2', name: '项目二' })
|
||||
const id = opened.project.id
|
||||
const planned = 'pre-lead-session'
|
||||
await store.mutate(s => { s.projects[id].seats.lead.plannedSessionId = planned })
|
||||
fake.addSession(planned)
|
||||
const enabled = await service.enable(id)
|
||||
assert.equal(enabled.project.status, 'ready')
|
||||
assert.equal(seatById(enabled, 'lead').sessionId, planned)
|
||||
assert.equal(fake.calls.create.filter(c => c.sessionId === planned).length, 0)
|
||||
assert.equal(fake.calls.create.length, 9)
|
||||
})
|
||||
|
||||
test('返回 ID 不一致:立即停止后续创建并记录', async () => {
|
||||
const { service, fake } = await setupService()
|
||||
fake.control.mismatchCreateOrder = 1
|
||||
const opened = await service.open({ path: '/p3', name: '项目三' })
|
||||
const enabled = await service.enable(opened.project.id)
|
||||
assert.equal(fake.calls.create.length, 1)
|
||||
assert.equal(enabled.project.status, 'error')
|
||||
const failed = enabled.project.seats.filter(s => s.status === 'failed')
|
||||
assert.equal(failed.length, 1)
|
||||
assert.match(failed[0].error, /不一致/)
|
||||
assert.equal(enabled.project.seats.filter(s => s.status === 'pending').length, 9)
|
||||
})
|
||||
|
||||
test('失败保留已完成绑定,重试只补未完成项', async () => {
|
||||
const { service, fake } = await setupService()
|
||||
fake.control.failCreateOrder = 2
|
||||
const opened = await service.open({ path: '/p4', name: '项目四' })
|
||||
const id = opened.project.id
|
||||
const first = await service.enable(id)
|
||||
assert.equal(first.project.status, 'error')
|
||||
const boundBefore = first.project.seats.filter(s => s.status === 'bound').map(s => s.sessionId)
|
||||
assert.equal(boundBefore.length, 9)
|
||||
|
||||
fake.control.failCreateOrder = null
|
||||
const createdBefore = fake.calls.create.length
|
||||
const second = await service.enable(id)
|
||||
assert.equal(second.project.status, 'ready')
|
||||
const nowBound = second.project.seats.filter(s => s.status === 'bound').map(s => s.sessionId)
|
||||
for (const sid of boundBefore) assert.ok(nowBound.includes(sid), '已绑定的会话 ID 不能变')
|
||||
assert.equal(nowBound.length, 10)
|
||||
assert.equal(fake.calls.create.length, createdBefore + 1, '重试只应补一个会话')
|
||||
})
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { SEAT_IDS, SEATS, SEAT_GROUPS, seatLabel, isSeatId } from '../src/shared/roles.js'
|
||||
|
||||
test('十席固定且显示名两字', () => {
|
||||
assert.equal(SEAT_IDS.length, 10)
|
||||
assert.equal(new Set(SEAT_IDS).size, 10)
|
||||
for (const id of SEAT_IDS) {
|
||||
assert.equal(SEATS[id].id, id)
|
||||
assert.equal(SEATS[id].label.length, 2, `${id} 显示名必须是两字`)
|
||||
assert.ok(SEATS[id].duty && SEATS[id].duty.length > 0)
|
||||
assert.ok(SEATS[id].responsibility && SEATS[id].responsibility.length > 0)
|
||||
}
|
||||
})
|
||||
|
||||
test('分组覆盖全部十席且结构正确', () => {
|
||||
const all = [...SEAT_GROUPS.lead, ...SEAT_GROUPS.sansheng, ...SEAT_GROUPS.liubu].sort()
|
||||
assert.deepEqual(all, [...SEAT_IDS].sort())
|
||||
assert.deepEqual([...SEAT_GROUPS.lead], ['lead'])
|
||||
assert.deepEqual([...SEAT_GROUPS.sansheng], ['zhongshu', 'shangshu', 'menxia'])
|
||||
assert.equal(SEAT_GROUPS.liubu.length, 6)
|
||||
})
|
||||
|
||||
test('seatLabel / isSeatId', () => {
|
||||
assert.equal(seatLabel('gongbu'), '工部')
|
||||
assert.equal(seatLabel('lead'), '丞相')
|
||||
assert.ok(isSeatId('lead'))
|
||||
assert.ok(!isSeatId('nope'))
|
||||
})
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { writeFile } from 'node:fs/promises'
|
||||
import { SanshengStore, StoreError } from '../src/host/store.js'
|
||||
import { emptyState } from '../src/shared/schema.js'
|
||||
import { tempStateFile } from './fake-ctx.js'
|
||||
|
||||
test('缺少文件加载为空状态', async () => {
|
||||
const file = await tempStateFile()
|
||||
const store = new SanshengStore(file)
|
||||
await store.load()
|
||||
assert.deepEqual(store.snapshot(), emptyState())
|
||||
})
|
||||
|
||||
test('保存后可重新加载,项目含十席', async () => {
|
||||
const file = await tempStateFile()
|
||||
const store = new SanshengStore(file)
|
||||
await store.load()
|
||||
await store.mutate(() => { store.ensureProjectRecord({ id: 'ws-1', name: '项目一', workspaceId: 'ws-1', path: '/p1' }) })
|
||||
const again = new SanshengStore(file)
|
||||
await again.load()
|
||||
const p = again.get('ws-1')
|
||||
assert.equal(p.name, '项目一')
|
||||
assert.equal(Object.keys(p.seats).length, 10)
|
||||
})
|
||||
|
||||
test('非法 JSON 视为损坏并抛错(不回退空状态)', async () => {
|
||||
const file = await tempStateFile()
|
||||
await writeFile(file, '{ 不是 json', 'utf8')
|
||||
const store = new SanshengStore(file)
|
||||
await assert.rejects(() => store.load(), err => err instanceof StoreError && err.code === 'sansheng/state-corrupt')
|
||||
})
|
||||
|
||||
test('错误版本视为损坏', async () => {
|
||||
const file = await tempStateFile()
|
||||
await writeFile(file, JSON.stringify({ version: 9, projects: {} }), 'utf8')
|
||||
const store = new SanshengStore(file)
|
||||
await assert.rejects(() => store.load(), err => err.code === 'sansheng/state-corrupt')
|
||||
})
|
||||
|
||||
test('seats 不是固定十席视为损坏', async () => {
|
||||
const file = await tempStateFile()
|
||||
const state = emptyState()
|
||||
state.projects.bad = { id: 'bad', name: 'x', workspaceId: null, path: null, status: 'pending', revision: 0, seats: {} }
|
||||
await writeFile(file, JSON.stringify(state), 'utf8')
|
||||
const store = new SanshengStore(file)
|
||||
await assert.rejects(() => store.load(), err => err.code === 'sansheng/state-corrupt')
|
||||
})
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { apply, name, inject } from '../index.js'
|
||||
import { createFakeHost, tempStateFile } from './fake-ctx.js'
|
||||
|
||||
test('apply 注册提示词与 /api/sansheng 路由并可处理请求', async () => {
|
||||
const fake = createFakeHost()
|
||||
const statePath = await tempStateFile()
|
||||
await apply(fake.ctx, { statePath })
|
||||
|
||||
assert.equal(name, 'sansheng')
|
||||
assert.ok(inject.includes('connection'))
|
||||
assert.ok(fake.getPromptSection(), '应注册 systemPrompt section')
|
||||
|
||||
const route = fake.getRoute()
|
||||
assert.equal(route.path, '/api/sansheng')
|
||||
assert.deepEqual(route.methods, ['POST'])
|
||||
|
||||
const res = await route.fetch({ json: async () => ({ endpoint: 'open', payload: { path: '/w', name: '接线项目' } }) })
|
||||
const body = await res.json()
|
||||
assert.ok(body.ok)
|
||||
assert.equal(body.value.project.seats.length, 10)
|
||||
})
|
||||
Loading…
Reference in New Issue