feat(v1.0.0): 修复派工工具注册并增加尚书汇总
This commit is contained in:
parent
b0a46428f9
commit
ebc3649d6d
|
|
@ -1,4 +1,4 @@
|
||||||
# 三省六部(dsh-sansheng)· v0.5.2
|
# 三省六部(dsh-sansheng)· v1.0.0
|
||||||
|
|
||||||
在 DSH 里为每个项目提供固定的十席角色(丞相、中书、门下、尚书、吏部、户部、礼部、兵部、刑部、工部),
|
在 DSH 里为每个项目提供固定的十席角色(丞相、中书、门下、尚书、吏部、户部、礼部、兵部、刑部、工部),
|
||||||
每席绑定一个独立的原生 root Session,模型与补充说明按项目独立保存。中间复用宿主原生会话,不替换聊天引擎。
|
每席绑定一个独立的原生 root Session,模型与补充说明按项目独立保存。中间复用宿主原生会话,不替换聊天引擎。
|
||||||
|
|
@ -11,8 +11,11 @@
|
||||||
- 任务记录区分待执行/已派工/执行中/已完成/已取消/失败,支持重复投递去重、取消后迟到结果留档(不改回取消状态)。
|
- 任务记录区分待执行/已派工/执行中/已完成/已取消/失败,支持重复投递去重、取消后迟到结果留档(不改回取消状态)。
|
||||||
- 打开部门对话只核实并进入原绑定会话,不会重复新建;会话被删除时标记「会话缺失」,由用户确认重建,旧历史保留;部门标题固定为两字角色名。
|
- 打开部门对话只核实并进入原绑定会话,不会重复新建;会话被删除时标记「会话缺失」,由用户确认重建,旧历史保留;部门标题固定为两字角色名。
|
||||||
- 模型选择立即生效并同步界面,不再出现选完又跳回「请选择模型」;模型按项目/席位保存,开启部门或下次打开继续使用。
|
- 模型选择立即生效并同步界面,不再出现选完又跳回「请选择模型」;模型按项目/席位保存,开启部门或下次打开继续使用。
|
||||||
|
- 派工工具随席位绑定即时注册:新建、恢复、重建后同一次 DSH 启动内即可派工;重新绑定后旧会话失去该席位工具权限。
|
||||||
|
- 派工失败明确区分「本席派工工具未就绪」「目标部门未开启」「任务投递失败」,以项目真实席位绑定和会话 ID 为准。
|
||||||
|
- 尚书可按需汇总项目真实任务与结果,明确区分「已派工/已收到」和「已完成」,不拦截丞相直接派工。
|
||||||
|
|
||||||
**本包尚未安装到任何 DSH profile,也未改动用户的日常 DSH 配置。**
|
**本包尚未安装到用户的日常 DSH profile,也未改动日常 DSH 配置。**
|
||||||
|
|
||||||
## 目录
|
## 目录
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1230,6 +1230,7 @@ function apply(ctx) {
|
||||||
const [artifacts, setArtifacts] = (0, import_react.useState)([]);
|
const [artifacts, setArtifacts] = (0, import_react.useState)([]);
|
||||||
const [taskFormOpen, setTaskFormOpen] = (0, import_react.useState)(false);
|
const [taskFormOpen, setTaskFormOpen] = (0, import_react.useState)(false);
|
||||||
const [taskDraft, setTaskDraft] = (0, import_react.useState)({ title: "", goal: "", ownerSeatId: SEAT_IDS[0] });
|
const [taskDraft, setTaskDraft] = (0, import_react.useState)({ title: "", goal: "", ownerSeatId: SEAT_IDS[0] });
|
||||||
|
const [summaryBusy, setSummaryBusy] = (0, import_react.useState)(false);
|
||||||
const [artifactFormOpen, setArtifactFormOpen] = (0, import_react.useState)(false);
|
const [artifactFormOpen, setArtifactFormOpen] = (0, import_react.useState)(false);
|
||||||
const [artifactDraft, setArtifactDraft] = (0, import_react.useState)({ title: "", path: "", summary: "" });
|
const [artifactDraft, setArtifactDraft] = (0, import_react.useState)({ title: "", path: "", summary: "" });
|
||||||
const alive = (0, import_react.useRef)(true);
|
const alive = (0, import_react.useRef)(true);
|
||||||
|
|
@ -1563,6 +1564,23 @@ function apply(ctx) {
|
||||||
if (alive.current) setBusy(false);
|
if (alive.current) setBusy(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
async function summarizeByShangshu() {
|
||||||
|
const projectId = view && view.project ? view.project.id : null;
|
||||||
|
if (!projectId) return;
|
||||||
|
setSummaryBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const result = await request("shangshuSummary", { projectId });
|
||||||
|
if (!alive.current) return;
|
||||||
|
if (!result || !result.sessionId) throw new Error("宿主没有返回尚书会话");
|
||||||
|
setNotice("已请尚书汇总当前任务,正在打开尚书会话…");
|
||||||
|
navigateToSession(result.sessionId);
|
||||||
|
} catch (summaryError) {
|
||||||
|
if (alive.current) setError(summaryError && summaryError.message ? summaryError.message : "尚书汇总请求失败");
|
||||||
|
} finally {
|
||||||
|
if (alive.current) setSummaryBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
async function cancelTask(taskId) {
|
async function cancelTask(taskId) {
|
||||||
const projectId = view && view.project ? view.project.id : null;
|
const projectId = view && view.project ? view.project.id : null;
|
||||||
if (!projectId) return;
|
if (!projectId) return;
|
||||||
|
|
@ -1832,7 +1850,14 @@ function apply(ctx) {
|
||||||
"div",
|
"div",
|
||||||
{ className: "ssw-page-head" },
|
{ className: "ssw-page-head" },
|
||||||
(0, import_react.createElement)("strong", null, "任务 · " + tasks.length),
|
(0, import_react.createElement)("strong", null, "任务 · " + tasks.length),
|
||||||
(0, import_react.createElement)("button", { type: "button", className: "ssw-primary", onClick: () => setTaskFormOpen((value) => !value) }, taskFormOpen ? "收起" : "新建任务")
|
(0, import_react.createElement)(
|
||||||
|
"div",
|
||||||
|
{ style: { display: "flex", alignItems: "center", gap: "10px" } },
|
||||||
|
(0, import_react.createElement)("button", { type: "button", className: "ssw-link", disabled: busy || summaryBusy || tasks.length === 0, onClick: () => {
|
||||||
|
void summarizeByShangshu();
|
||||||
|
} }, summaryBusy ? "汇总中…" : "尚书汇总"),
|
||||||
|
(0, import_react.createElement)("button", { type: "button", className: "ssw-primary", onClick: () => setTaskFormOpen((value) => !value) }, taskFormOpen ? "收起" : "新建任务")
|
||||||
|
)
|
||||||
),
|
),
|
||||||
taskFormOpen ? (0, import_react.createElement)(
|
taskFormOpen ? (0, import_react.createElement)(
|
||||||
"form",
|
"form",
|
||||||
|
|
@ -1997,24 +2022,41 @@ function apply(ctx) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function SanshengNavFallback() {
|
function SanshengNavFallback() {
|
||||||
|
const hasBetterSidebar = !!get("betterSidebar");
|
||||||
const [mode, setMode] = (0, import_react.useState)("pending");
|
const [mode, setMode] = (0, import_react.useState)("pending");
|
||||||
(0, import_react.useEffect)(() => {
|
(0, import_react.useEffect)(() => {
|
||||||
const hasBetter = !!get("betterSidebar");
|
let opened = false;
|
||||||
backToChat();
|
try {
|
||||||
if (!hasBetter) {
|
opened = openRightWorkbench();
|
||||||
const timer = setTimeout(() => {
|
} catch {
|
||||||
if (!openRightWorkbench()) setMode("inline");
|
opened = false;
|
||||||
}, 400);
|
|
||||||
return () => clearTimeout(timer);
|
|
||||||
}
|
}
|
||||||
|
if (opened) {
|
||||||
|
setMode("docked");
|
||||||
|
backToChat();
|
||||||
|
return void 0;
|
||||||
|
}
|
||||||
|
if (!hasBetterSidebar) {
|
||||||
|
setMode("inline");
|
||||||
|
return void 0;
|
||||||
|
}
|
||||||
|
backToChat();
|
||||||
|
let openedLater = false;
|
||||||
for (const delay of [200, 600, 1200, 2e3]) {
|
for (const delay of [200, 600, 1200, 2e3]) {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
try {
|
try {
|
||||||
if (openRightWorkbench()) backToChat();
|
if (!openedLater && openRightWorkbench()) {
|
||||||
|
openedLater = true;
|
||||||
|
backToChat();
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
}
|
}
|
||||||
}, delay);
|
}, delay);
|
||||||
}
|
}
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!openedLater) setMode("inline");
|
||||||
|
}, 2600);
|
||||||
|
return void 0;
|
||||||
}, []);
|
}, []);
|
||||||
(0, import_react.useEffect)(() => {
|
(0, import_react.useEffect)(() => {
|
||||||
if (mode !== "docked") return;
|
if (mode !== "docked") return;
|
||||||
|
|
@ -2030,7 +2072,7 @@ function apply(ctx) {
|
||||||
(0, import_react.createElement)(
|
(0, import_react.createElement)(
|
||||||
"div",
|
"div",
|
||||||
{ className: "ssw-inline-bar" },
|
{ className: "ssw-inline-bar" },
|
||||||
(0, import_react.createElement)("span", null, "右侧工作台未能打开,先显示在这里"),
|
(0, import_react.createElement)("span", null, "工作台 · 内嵌模式"),
|
||||||
(0, import_react.createElement)("button", { type: "button", className: "ssw-link", onClick: backToChat }, "返回对话")
|
(0, import_react.createElement)("button", { type: "button", className: "ssw-link", onClick: backToChat }, "返回对话")
|
||||||
),
|
),
|
||||||
(0, import_react.createElement)(SanshengWorkbench, {})
|
(0, import_react.createElement)(SanshengWorkbench, {})
|
||||||
|
|
|
||||||
|
|
@ -31,7 +31,7 @@ export function apply(ctx, config = {}) {
|
||||||
const handle = createApiHandler(service)
|
const handle = createApiHandler(service)
|
||||||
|
|
||||||
ctx.effect(() => installPromptSection(ctx, { store }), 'sansheng: prompt section')
|
ctx.effect(() => installPromptSection(ctx, { store }), 'sansheng: prompt section')
|
||||||
ctx.effect(() => installSeatTools(ctx, { store, service }), 'sansheng: seat tools')
|
ctx.effect(() => installSeatTools(ctx, { store, service, provisioner }), 'sansheng: seat tools')
|
||||||
|
|
||||||
// 复用宿主共享 /api 通道;浏览器带会话 Cookie 认证。
|
// 复用宿主共享 /api 通道;浏览器带会话 Cookie 认证。
|
||||||
ctx.effect(() => ctx.connection.fetch.register({
|
ctx.effect(() => ctx.connection.fetch.register({
|
||||||
|
|
|
||||||
|
|
@ -346,6 +346,7 @@ export function apply(ctx) {
|
||||||
const [artifacts, setArtifacts] = useState([])
|
const [artifacts, setArtifacts] = useState([])
|
||||||
const [taskFormOpen, setTaskFormOpen] = useState(false)
|
const [taskFormOpen, setTaskFormOpen] = useState(false)
|
||||||
const [taskDraft, setTaskDraft] = useState({ title: '', goal: '', ownerSeatId: SEAT_IDS[0] })
|
const [taskDraft, setTaskDraft] = useState({ title: '', goal: '', ownerSeatId: SEAT_IDS[0] })
|
||||||
|
const [summaryBusy, setSummaryBusy] = useState(false)
|
||||||
const [artifactFormOpen, setArtifactFormOpen] = useState(false)
|
const [artifactFormOpen, setArtifactFormOpen] = useState(false)
|
||||||
const [artifactDraft, setArtifactDraft] = useState({ title: '', path: '', summary: '' })
|
const [artifactDraft, setArtifactDraft] = useState({ title: '', path: '', summary: '' })
|
||||||
const alive = useRef(true)
|
const alive = useRef(true)
|
||||||
|
|
@ -666,6 +667,23 @@ export function apply(ctx) {
|
||||||
} finally { if (alive.current) setBusy(false) }
|
} finally { if (alive.current) setBusy(false) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function summarizeByShangshu() {
|
||||||
|
const projectId = view && view.project ? view.project.id : null
|
||||||
|
if (!projectId) return
|
||||||
|
setSummaryBusy(true); setError(null)
|
||||||
|
try {
|
||||||
|
const result = await request('shangshuSummary', { projectId })
|
||||||
|
if (!alive.current) return
|
||||||
|
if (!result || !result.sessionId) throw new Error('宿主没有返回尚书会话')
|
||||||
|
setNotice('已请尚书汇总当前任务,正在打开尚书会话…')
|
||||||
|
navigateToSession(result.sessionId)
|
||||||
|
} catch (summaryError) {
|
||||||
|
if (alive.current) setError(summaryError && summaryError.message ? summaryError.message : '尚书汇总请求失败')
|
||||||
|
} finally {
|
||||||
|
if (alive.current) setSummaryBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function cancelTask(taskId) {
|
async function cancelTask(taskId) {
|
||||||
const projectId = view && view.project ? view.project.id : null
|
const projectId = view && view.project ? view.project.id : null
|
||||||
if (!projectId) return
|
if (!projectId) return
|
||||||
|
|
@ -878,7 +896,9 @@ export function apply(ctx) {
|
||||||
const taskView = h('section', { className: 'ssw-page' },
|
const taskView = h('section', { className: 'ssw-page' },
|
||||||
h('div', { className: 'ssw-page-head' },
|
h('div', { className: 'ssw-page-head' },
|
||||||
h('strong', null, '任务 · ' + tasks.length),
|
h('strong', null, '任务 · ' + tasks.length),
|
||||||
h('button', { type: 'button', className: 'ssw-primary', onClick: () => setTaskFormOpen(value => !value) }, taskFormOpen ? '收起' : '新建任务')),
|
h('div', { style: { display: 'flex', alignItems: 'center', gap: '10px' } },
|
||||||
|
h('button', { type: 'button', className: 'ssw-link', disabled: busy || summaryBusy || tasks.length === 0, onClick: () => { void summarizeByShangshu() } }, summaryBusy ? '汇总中…' : '尚书汇总'),
|
||||||
|
h('button', { type: 'button', className: 'ssw-primary', onClick: () => setTaskFormOpen(value => !value) }, taskFormOpen ? '收起' : '新建任务'))),
|
||||||
taskFormOpen ? h('form', { className: 'ssw-form', onSubmit: event => { event.preventDefault(); void createTask() } },
|
taskFormOpen ? h('form', { className: 'ssw-form', onSubmit: event => { event.preventDefault(); void createTask() } },
|
||||||
h('label', { className: 'ssw-label' }, '标题'),
|
h('label', { className: 'ssw-label' }, '标题'),
|
||||||
h('input', { className: 'ssw-field', value: taskDraft.title, placeholder: '交给部门做什么', onChange: event => setTaskDraft({ ...taskDraft, title: event.target.value }) }),
|
h('input', { className: 'ssw-field', value: taskDraft.title, placeholder: '交给部门做什么', onChange: event => setTaskDraft({ ...taskDraft, title: event.target.value }) }),
|
||||||
|
|
@ -1001,22 +1021,34 @@ export function apply(ctx) {
|
||||||
if (layout && isFn(layout.selectPanel)) { try { layout.selectPanel(null) } catch { /* 忽略 */ } }
|
if (layout && isFn(layout.selectPanel)) { try { layout.selectPanel(null) } catch { /* 忽略 */ } }
|
||||||
}
|
}
|
||||||
function SanshengNavFallback() {
|
function SanshengNavFallback() {
|
||||||
|
// 点击左侧「三省六部」整行时,优先把工作台停靠到右侧;打不开就在主区内嵌显示。
|
||||||
|
// 关键:openRightWorkbench 必须在组件仍挂载时同步尝试。旧逻辑先 backToChat,
|
||||||
|
// 组件随即卸载,定时器里的 setMode('inline') 落在已卸载实例上,主区就永远空白。
|
||||||
|
const hasBetterSidebar = !!get('betterSidebar')
|
||||||
const [mode, setMode] = useState('pending')
|
const [mode, setMode] = useState('pending')
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// 整行点击会先把主区切成本页(此时会话面板已卸载,右栏开不了)。
|
let opened = false
|
||||||
// 立刻切回会话,然后在会话重新挂载后用全局定时器重试打开右栏;
|
try { opened = openRightWorkbench() } catch { opened = false }
|
||||||
// 这些定时器不随本组件卸载取消,否则切回会话就把自己“清理”掉了。
|
if (opened) {
|
||||||
const hasBetter = !!get('betterSidebar')
|
setMode('docked')
|
||||||
backToChat()
|
backToChat()
|
||||||
if (!hasBetter) {
|
return undefined
|
||||||
const timer = setTimeout(() => { if (!openRightWorkbench()) setMode('inline') }, 400)
|
|
||||||
return () => clearTimeout(timer)
|
|
||||||
}
|
}
|
||||||
|
if (!hasBetterSidebar) {
|
||||||
|
setMode('inline')
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
// 桌面右栏宿主:先切回会话,再等会话重新挂载后重试打开右栏。
|
||||||
|
// 这些定时器不随本组件卸载取消,否则切回会话就把自己“清理”掉了。
|
||||||
|
backToChat()
|
||||||
|
let openedLater = false
|
||||||
for (const delay of [200, 600, 1200, 2000]) {
|
for (const delay of [200, 600, 1200, 2000]) {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
try { if (openRightWorkbench()) backToChat() } catch { /* 忽略 */ }
|
try { if (!openedLater && openRightWorkbench()) { openedLater = true; backToChat() } } catch { /* 忽略 */ }
|
||||||
}, delay)
|
}, delay)
|
||||||
}
|
}
|
||||||
|
setTimeout(() => { if (!openedLater) setMode('inline') }, 2600)
|
||||||
|
return undefined
|
||||||
}, [])
|
}, [])
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (mode !== 'docked') return
|
if (mode !== 'docked') return
|
||||||
|
|
@ -1028,7 +1060,7 @@ export function apply(ctx) {
|
||||||
if (mode === 'docked') return null
|
if (mode === 'docked') return null
|
||||||
return h('div', { className: 'ssw-tab-body' },
|
return h('div', { className: 'ssw-tab-body' },
|
||||||
h('div', { className: 'ssw-inline-bar' },
|
h('div', { className: 'ssw-inline-bar' },
|
||||||
h('span', null, '右侧工作台未能打开,先显示在这里'),
|
h('span', null, '工作台 · 内嵌模式'),
|
||||||
h('button', { type: 'button', className: 'ssw-link', onClick: backToChat }, '返回对话'),
|
h('button', { type: 'button', className: 'ssw-link', onClick: backToChat }, '返回对话'),
|
||||||
),
|
),
|
||||||
h(SanshengWorkbench, {}),
|
h(SanshengWorkbench, {}),
|
||||||
|
|
|
||||||
|
|
@ -62,6 +62,10 @@ export function createApiHandler(service) {
|
||||||
return { ok: true, value: await service.models() }
|
return { ok: true, value: await service.models() }
|
||||||
case 'tasks':
|
case 'tasks':
|
||||||
return { ok: true, value: await service.tasks(requireProjectId(payload)) }
|
return { ok: true, value: await service.tasks(requireProjectId(payload)) }
|
||||||
|
case 'taskSummary':
|
||||||
|
return { ok: true, value: await service.taskSummary(requireProjectId(payload)) }
|
||||||
|
case 'shangshuSummary':
|
||||||
|
return { ok: true, value: await service.shangshuSummary(requireProjectId(payload)) }
|
||||||
case 'taskCreate':
|
case 'taskCreate':
|
||||||
return { ok: true, value: await service.taskCreate(requireProjectId(payload), payload ?? {}) }
|
return { ok: true, value: await service.taskCreate(requireProjectId(payload), payload ?? {}) }
|
||||||
case 'taskDispatch':
|
case 'taskDispatch':
|
||||||
|
|
|
||||||
|
|
@ -22,6 +22,12 @@ export function renderSeatPrompt({ project, seatId, seat }) {
|
||||||
'',
|
'',
|
||||||
'回报硬性规则:你必须使用 sansheng_task_report 工具回报真实状态(running 执行中、done 完成、failed 失败);done 必须附真实结果(文件路径、输出或验证结果),不得虚报。丞相不能代替部门报告。',
|
'回报硬性规则:你必须使用 sansheng_task_report 工具回报真实状态(running 执行中、done 完成、failed 失败);done 必须附真实结果(文件路径、输出或验证结果),不得虚报。丞相不能代替部门报告。',
|
||||||
)
|
)
|
||||||
|
if (seatId === 'shangshu') {
|
||||||
|
lines.push(
|
||||||
|
'',
|
||||||
|
'统筹汇总规则:丞相可以直接向六部派工,你不需要拦截或重新分配;当用户或丞相要求汇总时,请用 sansheng_task_list / sansheng_task_result 读取本项目真实任务与结果,按状态汇总,并明确区分「已派工/已收到」和「已完成」。',
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
lines.push('只在本项目本席会话内工作;不要修改其他项目或其他席的配置,也不要替用户提升权限。')
|
lines.push('只在本项目本席会话内工作;不要修改其他项目或其他席的配置,也不要替用户提升权限。')
|
||||||
return lines.join('\n')
|
return lines.join('\n')
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,20 @@ function isNotFound(error) {
|
||||||
export function createProvisioner({ store, host, now = () => Date.now() }) {
|
export function createProvisioner({ store, host, now = () => Date.now() }) {
|
||||||
const locks = new Map()
|
const locks = new Map()
|
||||||
const titlesEnsured = new Set()
|
const titlesEnsured = new Set()
|
||||||
|
// 席位绑定变化事件:工具注册必须挂到“绑定成功”这一步,而不是只靠可能先到的 agent/created。
|
||||||
|
const seatListeners = new Set()
|
||||||
|
function onSeatChange(listener) {
|
||||||
|
if (typeof listener !== 'function') return () => {}
|
||||||
|
seatListeners.add(listener)
|
||||||
|
return () => { seatListeners.delete(listener) }
|
||||||
|
}
|
||||||
|
function emitSeatChange(event) {
|
||||||
|
for (const listener of [...seatListeners]) {
|
||||||
|
try { listener(event) } catch (error) {
|
||||||
|
console.warn(`[sansheng] 席位事件监听失败:${error?.message ?? error}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function withLock(key, fn) {
|
function withLock(key, fn) {
|
||||||
const prev = locks.get(key) ?? Promise.resolve()
|
const prev = locks.get(key) ?? Promise.resolve()
|
||||||
|
|
@ -42,6 +56,8 @@ export function createProvisioner({ store, host, now = () => Date.now() }) {
|
||||||
st.updatedAt = now()
|
st.updatedAt = now()
|
||||||
p.updatedAt = now()
|
p.updatedAt = now()
|
||||||
})
|
})
|
||||||
|
// 绑定已落库:通知工具层为这个会话安装本席工具(新建/恢复/重建都走这里)。
|
||||||
|
emitSeatChange({ type: 'bound', projectId, seatId, sessionId, previousSessionId: previousSessionId ?? null })
|
||||||
}
|
}
|
||||||
async function markFailed(projectId, seatId, message) {
|
async function markFailed(projectId, seatId, message) {
|
||||||
await store.mutate(s => {
|
await store.mutate(s => {
|
||||||
|
|
@ -53,15 +69,19 @@ export function createProvisioner({ store, host, now = () => Date.now() }) {
|
||||||
}
|
}
|
||||||
// 绑定记录还在,但宿主里的会话已经不存在:只标记,绝不自动补建。
|
// 绑定记录还在,但宿主里的会话已经不存在:只标记,绝不自动补建。
|
||||||
async function markMissing(projectId, seatId, message) {
|
async function markMissing(projectId, seatId, message) {
|
||||||
|
let previousSessionId = null
|
||||||
await store.mutate(s => {
|
await store.mutate(s => {
|
||||||
const p = s.projects[projectId]
|
const p = s.projects[projectId]
|
||||||
const st = p.seats[seatId]
|
const st = p.seats[seatId]
|
||||||
|
previousSessionId = st.sessionId ?? null
|
||||||
st.status = 'missing'
|
st.status = 'missing'
|
||||||
st.error = String(message)
|
st.error = String(message)
|
||||||
st.updatedAt = now()
|
st.updatedAt = now()
|
||||||
p.status = 'error'
|
p.status = 'error'
|
||||||
p.updatedAt = now()
|
p.updatedAt = now()
|
||||||
})
|
})
|
||||||
|
// 会话已不存在:撤销该席对旧会话的工具授权。
|
||||||
|
emitSeatChange({ type: 'missing', projectId, seatId, sessionId: null, previousSessionId })
|
||||||
}
|
}
|
||||||
async function markMismatch(projectId, seatId, planned, actual) {
|
async function markMismatch(projectId, seatId, planned, actual) {
|
||||||
await store.mutate(s => {
|
await store.mutate(s => {
|
||||||
|
|
@ -365,5 +385,5 @@ export function createProvisioner({ store, host, now = () => Date.now() }) {
|
||||||
for (const seatId of SEAT_IDS) await renameSeatTitle(projectId, seatId)
|
for (const seatId of SEAT_IDS) await renameSeatTitle(projectId, seatId)
|
||||||
}
|
}
|
||||||
|
|
||||||
return { enable, enableSeat, ensureSeat, openSeat, rebuildSeat, ensureTitles }
|
return { enable, enableSeat, ensureSeat, openSeat, rebuildSeat, ensureTitles, onSeatChange }
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -225,6 +225,108 @@ export class SanshengService {
|
||||||
return { tasks: [...(project.tasks ?? [])] }
|
return { tasks: [...(project.tasks ?? [])] }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 只读任务汇总:按状态/主责席位统计,并返回可追溯的任务明细。
|
||||||
|
async taskSummary(projectId) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
const project = this.store.get(projectId)
|
||||||
|
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
const tasks = Array.isArray(project.tasks) ? project.tasks : []
|
||||||
|
const statusCounts = {}
|
||||||
|
const seatCounts = {}
|
||||||
|
for (const task of tasks) {
|
||||||
|
const status = typeof task.status === 'string' ? task.status : 'unknown'
|
||||||
|
statusCounts[status] = (statusCounts[status] ?? 0) + 1
|
||||||
|
const seatId = task.ownerSeatId
|
||||||
|
if (!seatCounts[seatId]) seatCounts[seatId] = { total: 0, done: 0, running: 0, open: 0 }
|
||||||
|
const row = seatCounts[seatId]
|
||||||
|
row.total += 1
|
||||||
|
if (status === 'done') row.done += 1
|
||||||
|
else if (status === 'running') row.running += 1
|
||||||
|
else if (status !== 'cancelled') row.open += 1
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
projectId,
|
||||||
|
projectName: project.name,
|
||||||
|
revision: project.revision ?? 0,
|
||||||
|
total: tasks.length,
|
||||||
|
statusCounts,
|
||||||
|
seatCounts,
|
||||||
|
openTasks: tasks
|
||||||
|
.filter(task => task.status !== 'done' && task.status !== 'cancelled')
|
||||||
|
.map(task => task.id),
|
||||||
|
tasks: tasks.map(task => ({
|
||||||
|
id: task.id,
|
||||||
|
title: task.title,
|
||||||
|
status: task.status,
|
||||||
|
ownerSeatId: task.ownerSeatId,
|
||||||
|
ownerLabel: SEATS[task.ownerSeatId]?.label ?? task.ownerSeatId,
|
||||||
|
goal: task.goal ?? '',
|
||||||
|
requirement: task.requirement ?? '',
|
||||||
|
result: task.result ?? '',
|
||||||
|
note: task.note ?? '',
|
||||||
|
resultSessionId: task.resultSessionId ?? null,
|
||||||
|
deliveryState: task.deliveryState ?? 'none',
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 轻量版尚书汇总:只把当前真实任务快照发给尚书汇总,不改变丞相直派流程,不创建新任务。
|
||||||
|
async shangshuSummary(projectId) {
|
||||||
|
const summary = await this.taskSummary(projectId)
|
||||||
|
let project = this.store.get(projectId)
|
||||||
|
let seat = project?.seats?.shangshu
|
||||||
|
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
|
||||||
|
await this.provisioner.enableSeat(projectId, 'shangshu')
|
||||||
|
project = this.store.get(projectId)
|
||||||
|
seat = project?.seats?.shangshu
|
||||||
|
}
|
||||||
|
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
|
||||||
|
throw new ServiceError('sansheng/seat-unbound', '「尚书」的会话还没开启成功,请稍后重试')
|
||||||
|
}
|
||||||
|
const controller = this.host.sessionController
|
||||||
|
if (typeof controller?.prompt !== 'function') {
|
||||||
|
throw new ServiceError('sansheng/delivery-failed', '宿主未提供 prompt 接口,无法发送尚书汇总请求')
|
||||||
|
}
|
||||||
|
const clip = (value, max = 800) => {
|
||||||
|
const raw = typeof value === 'string' ? value.trim() : ''
|
||||||
|
return raw.length > max ? `${raw.slice(0, max)}…` : raw
|
||||||
|
}
|
||||||
|
const detail = summary.tasks.length === 0
|
||||||
|
? '当前项目还没有任务记录。'
|
||||||
|
: summary.tasks.map(task => {
|
||||||
|
const parts = [`${task.id} [${task.status}] ${task.ownerLabel}:${task.title}`]
|
||||||
|
if (task.goal) parts.push(`目标:${clip(task.goal)}`)
|
||||||
|
if (task.requirement) parts.push(`用户原话:${clip(task.requirement)}`)
|
||||||
|
if (task.result) parts.push(`结果:${clip(task.result)}`)
|
||||||
|
if (task.note) parts.push(`备注:${clip(task.note)}`)
|
||||||
|
return `- ${parts.join(';')}`
|
||||||
|
}).join('\n')
|
||||||
|
const statusText = Object.entries(summary.statusCounts).map(([status, count]) => `${status} ${count}`).join(',') || '无'
|
||||||
|
const text = [
|
||||||
|
`【尚书汇总】请汇总项目「${summary.projectName ?? projectId}」的真实任务进度。`,
|
||||||
|
`任务总数:${summary.total};状态统计:${statusText}。`,
|
||||||
|
'任务明细:',
|
||||||
|
detail,
|
||||||
|
'',
|
||||||
|
'汇总要求:',
|
||||||
|
'1. 按已完成 / 执行中 / 已派工 / 待执行 / 失败或取消分组汇总,列出任务 ID、主责部门、当前状态和关键结果。',
|
||||||
|
'2. 明确区分「已派工/已收到」和「已完成」,不要把已派工当成完成。',
|
||||||
|
'3. 只做汇总,不重派任务,不拦截丞相直接派工;指出仍未完成或需要复核的事项。',
|
||||||
|
].join('\n')
|
||||||
|
const requestId = randomUUID()
|
||||||
|
try {
|
||||||
|
await controller.prompt({
|
||||||
|
requestId,
|
||||||
|
sessionId: seat.sessionId,
|
||||||
|
mode: 'queue',
|
||||||
|
content: [{ type: 'text', text }],
|
||||||
|
}, new AbortController().signal)
|
||||||
|
} catch (error) {
|
||||||
|
throw new ServiceError('sansheng/delivery-failed', `尚书汇总请求发送失败:${error?.message ?? error}`)
|
||||||
|
}
|
||||||
|
return { ok: true, sessionId: seat.sessionId, summary }
|
||||||
|
}
|
||||||
|
|
||||||
async taskCreate(projectId, input = {}) {
|
async taskCreate(projectId, input = {}) {
|
||||||
await this.store.ensureLoaded()
|
await this.store.ensureLoaded()
|
||||||
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
|
|
||||||
|
|
@ -69,7 +69,20 @@ function seatToolDefinitions({ store, service }) {
|
||||||
required: ['targetSeatId', 'title'],
|
required: ['targetSeatId', 'title'],
|
||||||
},
|
},
|
||||||
async execute(args = {}, exec) {
|
async execute(args = {}, exec) {
|
||||||
const { project, seatId } = await locateSeat(service, exec)
|
// 区分三种失败:本席工具未就绪 / 目标部门未开启 / 任务投递失败;成功才回 ok:true。
|
||||||
|
let located
|
||||||
|
try {
|
||||||
|
located = await locateSeat(service, exec)
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
delivered: false,
|
||||||
|
reason: 'tool-not-ready',
|
||||||
|
error: `本席派工工具未就绪:${error?.message ?? error}`,
|
||||||
|
hint: '当前会话没有有效的席位绑定,不能派工;请从已绑定的丞相会话发起。',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const { project, seatId } = located
|
||||||
if (seatId !== 'lead') throw new Error('只有丞相可以派工,部门不能自行派工')
|
if (seatId !== 'lead') throw new Error('只有丞相可以派工,部门不能自行派工')
|
||||||
const targetSeatId = text(args.targetSeatId)
|
const targetSeatId = text(args.targetSeatId)
|
||||||
if (!SEAT_IDS.includes(targetSeatId) || targetSeatId === 'lead') throw new Error('目标必须是丞相以外的十席部门')
|
if (!SEAT_IDS.includes(targetSeatId) || targetSeatId === 'lead') throw new Error('目标必须是丞相以外的十席部门')
|
||||||
|
|
@ -92,10 +105,42 @@ function seatToolDefinitions({ store, service }) {
|
||||||
requirement,
|
requirement,
|
||||||
ownerSeatId: targetSeatId,
|
ownerSeatId: targetSeatId,
|
||||||
})
|
})
|
||||||
const dispatched = await service.taskDispatch(project.id, created.task.id, { force: true })
|
let dispatched
|
||||||
|
try {
|
||||||
|
dispatched = await service.taskDispatch(project.id, created.task.id, { force: true })
|
||||||
|
} catch (error) {
|
||||||
|
const code = String(error?.code ?? '')
|
||||||
|
const message = String(error?.message ?? error)
|
||||||
|
if (code === 'sansheng/seat-unbound' || /会话还没开启|seat-unbound|未开启/.test(message)) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
delivered: false,
|
||||||
|
reason: 'target-seat-unavailable',
|
||||||
|
taskId: created.task.id,
|
||||||
|
targetLabel: labelOf(targetSeatId),
|
||||||
|
error: `目标部门「${labelOf(targetSeatId)}」未开启,无法派工:${message}`,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
delivered: false,
|
||||||
|
reason: 'delivery-failed',
|
||||||
|
taskId: created.task.id,
|
||||||
|
targetLabel: labelOf(targetSeatId),
|
||||||
|
error: `任务投递失败:${message}`,
|
||||||
|
}
|
||||||
|
}
|
||||||
const result = okTask(dispatched.task)
|
const result = okTask(dispatched.task)
|
||||||
if (!dispatched.delivered) {
|
if (!dispatched.delivered) {
|
||||||
return { ...result, ok: false, delivered: false, taskId: created.task.id, error: dispatched.task.note || '投递失败,未送达部门会话' }
|
return {
|
||||||
|
...result,
|
||||||
|
ok: false,
|
||||||
|
delivered: false,
|
||||||
|
reason: 'delivery-failed',
|
||||||
|
taskId: created.task.id,
|
||||||
|
targetLabel: labelOf(targetSeatId),
|
||||||
|
error: dispatched.task.note || '任务投递失败,未送达部门会话',
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
...result,
|
...result,
|
||||||
|
|
@ -217,18 +262,26 @@ export function createSeatToolDefinitions(options) {
|
||||||
return seatToolDefinitions(options)
|
return seatToolDefinitions(options)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function installSeatTools(ctx, { store, service }) {
|
export function installSeatTools(ctx, { store, service, provisioner }) {
|
||||||
const installed = new Map()
|
|
||||||
const defs = createSeatToolDefinitions({ store, service })
|
const defs = createSeatToolDefinitions({ store, service })
|
||||||
|
// sessionId -> { agent, disposers: Map<name, dispose>, registered: Set<name> }
|
||||||
|
const installs = new Map()
|
||||||
|
// 已绑定、但 agent 或工具系统尚未就绪的会话;等下一次席位事件/重扫再补装。
|
||||||
|
const retry = new Set()
|
||||||
let stopped = false
|
let stopped = false
|
||||||
|
|
||||||
|
const sessionIdOf = agent => agent?.session?.id ?? agent?.id ?? null
|
||||||
|
|
||||||
const disposeFor = sessionId => {
|
const disposeFor = sessionId => {
|
||||||
const list = installed.get(sessionId)
|
const record = installs.get(sessionId)
|
||||||
if (!list) return
|
if (!record) return
|
||||||
installed.delete(sessionId)
|
installs.delete(sessionId)
|
||||||
for (const dispose of list) {
|
retry.delete(sessionId)
|
||||||
|
for (const dispose of record.disposers.values()) {
|
||||||
try { dispose?.() } catch {}
|
try { dispose?.() } catch {}
|
||||||
}
|
}
|
||||||
|
record.disposers.clear()
|
||||||
|
record.registered.clear()
|
||||||
}
|
}
|
||||||
|
|
||||||
const findSeat = sessionId => {
|
const findSeat = sessionId => {
|
||||||
|
|
@ -241,42 +294,98 @@ export function installSeatTools(ctx, { store, service }) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 只给“仍是某席绑定会话”的 agent 注册;同会话同实例只装一次;换实例先卸旧再装。
|
||||||
const attach = agent => {
|
const attach = agent => {
|
||||||
if (stopped || !agent) return
|
if (stopped || !agent) return false
|
||||||
const sessionId = agent.session?.id ?? agent.id
|
const sessionId = sessionIdOf(agent)
|
||||||
if (!sessionId) return
|
if (!sessionId) return false
|
||||||
if (installed.has(sessionId)) return
|
if (!findSeat(sessionId)) return false
|
||||||
if (!findSeat(sessionId)) return
|
|
||||||
const agentTools = agent.ctx?.tools
|
const agentTools = agent.ctx?.tools
|
||||||
if (!agentTools || typeof agentTools.register !== 'function') return
|
if (!agentTools || typeof agentTools.register !== 'function') {
|
||||||
const disposers = []
|
retry.add(sessionId)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
let record = installs.get(sessionId)
|
||||||
|
if (record && record.agent !== agent) {
|
||||||
|
disposeFor(sessionId)
|
||||||
|
record = undefined
|
||||||
|
}
|
||||||
|
if (record && record.registered.size === defs.length) return true
|
||||||
|
if (!record) {
|
||||||
|
record = { agent, disposers: new Map(), registered: new Set() }
|
||||||
|
installs.set(sessionId, record)
|
||||||
|
}
|
||||||
for (const def of defs) {
|
for (const def of defs) {
|
||||||
|
if (record.registered.has(def.name)) continue
|
||||||
try {
|
try {
|
||||||
const dispose = agentTools.register(def)
|
const dispose = agentTools.register(def)
|
||||||
if (typeof dispose === 'function') disposers.push(dispose)
|
record.disposers.set(def.name, typeof dispose === 'function' ? dispose : null)
|
||||||
|
record.registered.add(def.name)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn(`sansheng: register ${def.name} failed: ${error?.message ?? error}`)
|
console.warn(`sansheng: register ${def.name} failed: ${error?.message ?? error}`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
installed.set(sessionId, disposers)
|
const complete = record.registered.size === defs.length
|
||||||
|
if (complete) retry.delete(sessionId)
|
||||||
|
else retry.add(sessionId)
|
||||||
|
return complete
|
||||||
|
}
|
||||||
|
|
||||||
|
const agentById = sessionId => {
|
||||||
|
try {
|
||||||
|
const direct = ctx.agents?.get?.(sessionId)
|
||||||
|
if (direct) return direct
|
||||||
|
} catch {}
|
||||||
|
try {
|
||||||
|
const list = ctx.agents?.list?.() ?? []
|
||||||
|
return list.find(agent => sessionIdOf(agent) === sessionId) ?? null
|
||||||
|
} catch { return null }
|
||||||
|
}
|
||||||
|
|
||||||
|
const attachBySessionId = sessionId => {
|
||||||
|
if (!sessionId) return false
|
||||||
|
if (!findSeat(sessionId)) { retry.delete(sessionId); return false }
|
||||||
|
const agent = agentById(sessionId)
|
||||||
|
if (!agent) { retry.add(sessionId); return false }
|
||||||
|
return attach(agent)
|
||||||
}
|
}
|
||||||
|
|
||||||
const scan = () => {
|
const scan = () => {
|
||||||
let agents = []
|
let agents = []
|
||||||
try { agents = ctx.agents?.list?.() ?? [] } catch {}
|
try { agents = ctx.agents?.list?.() ?? [] } catch {}
|
||||||
for (const agent of agents) void attach(agent)
|
for (const agent of agents) attach(agent)
|
||||||
|
for (const sessionId of [...retry]) attachBySessionId(sessionId)
|
||||||
}
|
}
|
||||||
|
|
||||||
scan()
|
scan()
|
||||||
void store.ensureLoaded().then(scan).catch(() => {})
|
void store.ensureLoaded().then(scan).catch(() => {})
|
||||||
const off = typeof ctx.on === 'function' ? ctx.on('agent/created', payload => {
|
|
||||||
const agent = payload?.agent ?? payload
|
// 主入口:席位绑定成功(新建/恢复/重建)后立即安装工具,不再依赖 agent/created 先于绑定保存的顺序。
|
||||||
attach(agent)
|
const offSeat = typeof provisioner?.onSeatChange === 'function'
|
||||||
}) : () => {}
|
? provisioner.onSeatChange(event => {
|
||||||
|
if (stopped || !event) return
|
||||||
|
// 重绑到新会话:旧会话立刻失去该席位的工具权限。
|
||||||
|
if (event.previousSessionId && event.previousSessionId !== event.sessionId) {
|
||||||
|
disposeFor(event.previousSessionId)
|
||||||
|
}
|
||||||
|
if (event.type === 'missing' || !event.sessionId) return
|
||||||
|
attachBySessionId(event.sessionId)
|
||||||
|
})
|
||||||
|
: () => {}
|
||||||
|
|
||||||
|
// 绑定已存在、会话稍后加载的顺序:agent/created 时再补装。
|
||||||
|
const offAgent = typeof ctx.on === 'function'
|
||||||
|
? ctx.on('agent/created', payload => {
|
||||||
|
const agent = payload?.agent ?? payload
|
||||||
|
attach(agent)
|
||||||
|
})
|
||||||
|
: () => {}
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
stopped = true
|
stopped = true
|
||||||
try { off?.() } catch {}
|
try { offSeat?.() } catch {}
|
||||||
for (const sessionId of [...installed.keys()]) disposeFor(sessionId)
|
try { offAgent?.() } catch {}
|
||||||
|
for (const sessionId of [...installs.keys()]) disposeFor(sessionId)
|
||||||
|
retry.clear()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,63 @@
|
||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { setupService, seatById } from './helpers.js'
|
||||||
|
import { createSeatToolDefinitions } from '../src/host/tools.js'
|
||||||
|
import { createApiHandler } from '../src/host/api.js'
|
||||||
|
|
||||||
|
function toolsOf(env) {
|
||||||
|
const defs = createSeatToolDefinitions({ store: env.store, service: env.service })
|
||||||
|
return Object.fromEntries(defs.map(def => [def.name, def]))
|
||||||
|
}
|
||||||
|
|
||||||
|
test('尚书汇总:丞相直派不被拦截,汇总请求发送到尚书真实会话', async () => {
|
||||||
|
const env = await setupService({ prompt: true })
|
||||||
|
const opened = await env.service.open({ path: '/shangshu-summary', name: '尚书汇总项目' })
|
||||||
|
const id = opened.project.id
|
||||||
|
const leadView = await env.service.enableSeat(id, 'lead')
|
||||||
|
const gongView = await env.service.enableSeat(id, 'gongbu')
|
||||||
|
const leadSessionId = seatById(leadView, 'lead').sessionId
|
||||||
|
const gongSessionId = seatById(gongView, 'gongbu').sessionId
|
||||||
|
const leadExec = { agent: env.fake.sessions.get(leadSessionId) }
|
||||||
|
|
||||||
|
const dispatched = await toolsOf(env).sansheng_dispatch_task.execute({
|
||||||
|
targetSeatId: 'gongbu',
|
||||||
|
title: '写页面',
|
||||||
|
goal: '完成页面',
|
||||||
|
requirement: '保留标题',
|
||||||
|
}, leadExec)
|
||||||
|
assert.equal(dispatched.ok, true, '丞相直派仍然成功')
|
||||||
|
assert.equal(dispatched.sessionId, gongSessionId)
|
||||||
|
assert.equal(dispatched.targetLabel, '工部')
|
||||||
|
|
||||||
|
const before = await env.service.tasks(id)
|
||||||
|
const result = await env.service.shangshuSummary(id)
|
||||||
|
const after = await env.service.tasks(id)
|
||||||
|
assert.equal(after.tasks.length, before.tasks.length, '汇总不能创建新任务')
|
||||||
|
assert.equal(result.summary.total, 1)
|
||||||
|
assert.equal(result.summary.statusCounts.dispatched, 1)
|
||||||
|
assert.equal(result.summary.tasks[0].ownerLabel, '工部')
|
||||||
|
assert.equal(result.summary.tasks[0].title, '写页面')
|
||||||
|
|
||||||
|
const shang = seatById(await env.service.project(id), 'shangshu')
|
||||||
|
assert.equal(shang.status, 'bound', '汇总会按需开启尚书会话')
|
||||||
|
assert.equal(result.sessionId, shang.sessionId)
|
||||||
|
const promptCall = env.fake.calls.prompt.at(-1)
|
||||||
|
assert.equal(promptCall.sessionId, shang.sessionId, '汇总请求必须发到尚书会话')
|
||||||
|
const text = promptCall.content[0].text
|
||||||
|
assert.match(text, /【尚书汇总】/)
|
||||||
|
assert.match(text, /写页面/)
|
||||||
|
assert.match(text, /已派工/)
|
||||||
|
assert.match(text, /不拦截丞相直接派工/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('尚书汇总 API 返回尚书会话和真实任务汇总', async () => {
|
||||||
|
const env = await setupService({ prompt: true })
|
||||||
|
const opened = await env.service.open({ path: '/shangshu-api', name: '尚书接口项目' })
|
||||||
|
const id = opened.project.id
|
||||||
|
await env.service.enableSeat(id, 'lead')
|
||||||
|
const handler = createApiHandler(env.service)
|
||||||
|
const out = await handler('shangshuSummary', { projectId: id })
|
||||||
|
assert.equal(out.ok, true)
|
||||||
|
assert.ok(out.value.sessionId)
|
||||||
|
assert.equal(out.value.summary.total, 0)
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,225 @@
|
||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { setupService, seatById } from './helpers.js'
|
||||||
|
import { createSeatToolDefinitions, installSeatTools } from '../src/host/tools.js'
|
||||||
|
|
||||||
|
// 构造一个带事件总线、且能模拟“创建事件先于绑定保存”的 ctx。
|
||||||
|
function makeEventedCtx(env) {
|
||||||
|
const listeners = new Map()
|
||||||
|
const registered = []
|
||||||
|
const disposed = []
|
||||||
|
const emit = (event, payload) => {
|
||||||
|
for (const fn of [...(listeners.get(event) ?? [])]) fn(payload)
|
||||||
|
}
|
||||||
|
const origCreate = env.fake.host.sessionController.create.bind(env.fake.host.sessionController)
|
||||||
|
env.fake.host.sessionController.create = async (args = {}) => {
|
||||||
|
const res = await origCreate(args)
|
||||||
|
const agent = env.fake.sessions.get(res.sessionId)
|
||||||
|
if (agent) {
|
||||||
|
agent.ctx = {
|
||||||
|
tools: {
|
||||||
|
register(def) {
|
||||||
|
registered.push({ sessionId: res.sessionId, name: def.name })
|
||||||
|
return () => disposed.push({ sessionId: res.sessionId, name: def.name })
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 真实宿主:create() 内部先触发 agent/created,此时席位绑定还没保存。
|
||||||
|
emit('agent/created', { agent })
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
const ctx = {
|
||||||
|
agents: { list: () => [...env.fake.sessions.values()], get: id => env.fake.sessions.get(id) },
|
||||||
|
on(event, fn) {
|
||||||
|
if (!listeners.has(event)) listeners.set(event, new Set())
|
||||||
|
listeners.get(event).add(fn)
|
||||||
|
return () => listeners.get(event)?.delete(fn)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return { ctx, registered, disposed, emit }
|
||||||
|
}
|
||||||
|
|
||||||
|
test('回归:创建事件先到、绑定后保存时,绑定成功即补装派工工具(无需重扫)', async () => {
|
||||||
|
const env = await setupService({ prompt: true })
|
||||||
|
const { ctx, registered } = makeEventedCtx(env)
|
||||||
|
const teardown = installSeatTools(ctx, { store: env.store, service: env.service, provisioner: env.provisioner })
|
||||||
|
try {
|
||||||
|
const opened = await env.service.open({ path: '/reg-order', name: '顺序项目' })
|
||||||
|
const id = opened.project.id
|
||||||
|
await env.service.enableSeat(id, 'lead')
|
||||||
|
const leadSessionId = seatById(await env.service.project(id), 'lead').sessionId
|
||||||
|
const forLead = registered.filter(item => item.sessionId === leadSessionId)
|
||||||
|
assert.equal(forLead.length, 5, '绑定保存后应立即安装 5 个部门工具')
|
||||||
|
assert.ok(forLead.some(item => item.name === 'sansheng_dispatch_task'), '丞相必须拿到 sansheng_dispatch_task')
|
||||||
|
} finally {
|
||||||
|
teardown()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('回归:同一活跃会话实例反复打开只注册一次', async () => {
|
||||||
|
const env = await setupService({ prompt: true })
|
||||||
|
const { ctx, registered, emit } = makeEventedCtx(env)
|
||||||
|
const teardown = installSeatTools(ctx, { store: env.store, service: env.service, provisioner: env.provisioner })
|
||||||
|
try {
|
||||||
|
const opened = await env.service.open({ path: '/reg-once', name: '一次项目' })
|
||||||
|
const id = opened.project.id
|
||||||
|
await env.service.enableSeat(id, 'lead')
|
||||||
|
const leadSessionId = seatById(await env.service.project(id), 'lead').sessionId
|
||||||
|
const agent = env.fake.sessions.get(leadSessionId)
|
||||||
|
assert.equal(registered.filter(item => item.sessionId === leadSessionId).length, 5)
|
||||||
|
// 同一 agent 实例再触发两次创建/打开事件,不应重复注册。
|
||||||
|
emit('agent/created', { agent })
|
||||||
|
emit('agent/created', { agent })
|
||||||
|
assert.equal(registered.filter(item => item.sessionId === leadSessionId).length, 5, '同一实例只注册一次')
|
||||||
|
} finally {
|
||||||
|
teardown()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('回归:重绑后旧会话失去该席工具、新会话注册工具,会话 ID 稳定', async () => {
|
||||||
|
const env = await setupService({ prompt: true })
|
||||||
|
const { ctx, registered, disposed } = makeEventedCtx(env)
|
||||||
|
const teardown = installSeatTools(ctx, { store: env.store, service: env.service, provisioner: env.provisioner })
|
||||||
|
try {
|
||||||
|
const opened = await env.service.open({ path: '/reg-rebind', name: '重绑项目' })
|
||||||
|
const id = opened.project.id
|
||||||
|
const leadView = await env.service.enableSeat(id, 'lead')
|
||||||
|
const oldSessionId = seatById(leadView, 'lead').sessionId
|
||||||
|
assert.equal(registered.filter(item => item.sessionId === oldSessionId).length, 5)
|
||||||
|
|
||||||
|
// 模拟宿主会话被删除,再重建到新会话。
|
||||||
|
env.fake.sessions.delete(oldSessionId)
|
||||||
|
await assert.rejects(() => env.service.openSeat(id, 'lead'), error => error.code === 'sansheng/session-missing')
|
||||||
|
const rebuilt = await env.service.rebuildSeat(id, 'lead', { expectedSessionId: oldSessionId })
|
||||||
|
const newSessionId = rebuilt.sessionId
|
||||||
|
assert.notEqual(newSessionId, oldSessionId)
|
||||||
|
const seat = seatById(await env.service.project(id), 'lead')
|
||||||
|
assert.equal(seat.sessionId, newSessionId, '重绑后会话 ID 应稳定为新 ID')
|
||||||
|
assert.deepEqual(seat.previousSessionIds, [oldSessionId])
|
||||||
|
assert.equal(registered.filter(item => item.sessionId === newSessionId).length, 5, '新会话应注册 5 个工具')
|
||||||
|
assert.equal(disposed.filter(item => item.sessionId === oldSessionId).length, 5, '旧会话的工具授权应被撤销')
|
||||||
|
} finally {
|
||||||
|
teardown()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
function toolsOf(env) {
|
||||||
|
const defs = createSeatToolDefinitions({ store: env.store, service: env.service })
|
||||||
|
return Object.fromEntries(defs.map(def => [def.name, def]))
|
||||||
|
}
|
||||||
|
|
||||||
|
test('派工失败区分:本席工具未就绪 / 目标部门未开启 / 投递失败', async () => {
|
||||||
|
// 1) 本席工具未就绪:普通会话调用派工
|
||||||
|
{
|
||||||
|
const env = await setupService({ prompt: true })
|
||||||
|
const opened = await env.service.open({ path: '/fail-ready', name: '就绪项目' })
|
||||||
|
await env.service.enableSeat(opened.project.id, 'lead')
|
||||||
|
const res = await toolsOf(env).sansheng_dispatch_task.execute({ targetSeatId: 'gongbu', title: 'x' }, { agent: { id: 'ordinary-x' } })
|
||||||
|
assert.equal(res.ok, false)
|
||||||
|
assert.equal(res.reason, 'tool-not-ready')
|
||||||
|
}
|
||||||
|
// 2) 目标部门未开启:工部创建会话失败
|
||||||
|
{
|
||||||
|
const env = await setupService({ prompt: true })
|
||||||
|
const opened = await env.service.open({ path: '/fail-target', name: '未开启项目' })
|
||||||
|
const leadView = await env.service.enableSeat(opened.project.id, 'lead')
|
||||||
|
const leadExec = { agent: env.fake.sessions.get(seatById(leadView, 'lead').sessionId) }
|
||||||
|
env.fake.control.failCreateOrder = env.fake.calls.create.length + 1
|
||||||
|
const res = await toolsOf(env).sansheng_dispatch_task.execute({ targetSeatId: 'gongbu', title: '写代码' }, leadExec)
|
||||||
|
assert.equal(res.ok, false)
|
||||||
|
assert.equal(res.reason, 'target-seat-unavailable')
|
||||||
|
assert.match(res.error, /工部/)
|
||||||
|
}
|
||||||
|
// 3) 投递失败:工部已绑定,但宿主 prompt 抛错
|
||||||
|
{
|
||||||
|
const env = await setupService({ prompt: true })
|
||||||
|
const opened = await env.service.open({ path: '/fail-deliver', name: '投递失败项目' })
|
||||||
|
const leadView = await env.service.enableSeat(opened.project.id, 'lead')
|
||||||
|
await env.service.enableSeat(opened.project.id, 'gongbu')
|
||||||
|
const leadExec = { agent: env.fake.sessions.get(seatById(leadView, 'lead').sessionId) }
|
||||||
|
env.fake.host.sessionController.prompt = async () => { throw new Error('模拟投递失败') }
|
||||||
|
const res = await toolsOf(env).sansheng_dispatch_task.execute({ targetSeatId: 'gongbu', title: '写代码' }, leadExec)
|
||||||
|
assert.equal(res.ok, false)
|
||||||
|
assert.equal(res.reason, 'delivery-failed')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('端到端:丞相派工落真实工部会话,任务记录/投递会话一致,并区分“收到”与“完成”', async () => {
|
||||||
|
const env = await setupService({ prompt: true })
|
||||||
|
const opened = await env.service.open({ path: '/e2e', name: '端到端项目' })
|
||||||
|
const id = opened.project.id
|
||||||
|
const leadView = await env.service.enableSeat(id, 'lead')
|
||||||
|
const gongView = await env.service.enableSeat(id, 'gongbu')
|
||||||
|
const leadSessionId = seatById(leadView, 'lead').sessionId
|
||||||
|
const gongSessionId = seatById(gongView, 'gongbu').sessionId
|
||||||
|
const tools = toolsOf(env)
|
||||||
|
const leadExec = { agent: env.fake.sessions.get(leadSessionId) }
|
||||||
|
const gongExec = { agent: env.fake.sessions.get(gongSessionId) }
|
||||||
|
|
||||||
|
const res = await tools.sansheng_dispatch_task.execute({
|
||||||
|
targetSeatId: 'gongbu', title: '生成 hello', goal: '生成 hello.txt', requirement: '工部生成 hello.txt 并回真实路径',
|
||||||
|
}, leadExec)
|
||||||
|
assert.equal(res.ok, true)
|
||||||
|
assert.equal(res.delivered, true)
|
||||||
|
assert.equal(res.sessionId, gongSessionId, '派工返回的会话必须是工部绑定会话')
|
||||||
|
|
||||||
|
const task = (await env.service.taskGet(id, res.taskId)).task
|
||||||
|
assert.equal(task.ownerSeatId, 'gongbu')
|
||||||
|
assert.equal(task.sessionId, gongSessionId, '任务记录的目标会话 ID 必须与工部绑定 ID 一致')
|
||||||
|
assert.equal(task.status, 'dispatched', '刚派工只代表“已收到/已投递”,不是完成')
|
||||||
|
|
||||||
|
const delivery = env.fake.calls.prompt.at(-1)
|
||||||
|
assert.equal(delivery.sessionId, gongSessionId, '任务必须投递进工部会话')
|
||||||
|
assert.match(delivery.content[0].text, /生成 hello/)
|
||||||
|
|
||||||
|
// 工部回报完成
|
||||||
|
await tools.sansheng_task_report.execute({
|
||||||
|
taskId: res.taskId, status: 'done', result: 'D:/out/hello.txt 已生成',
|
||||||
|
}, gongExec)
|
||||||
|
const done = (await env.service.taskGet(id, res.taskId)).task
|
||||||
|
assert.equal(done.status, 'done')
|
||||||
|
assert.equal(done.resultSessionId, gongSessionId, '完成结果必须来自工部真实会话')
|
||||||
|
assert.match(done.result, /hello\.txt/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('回归:注册失败可重试,后续事件补齐缺失工具', async () => {
|
||||||
|
const env = await setupService({ prompt: true })
|
||||||
|
const opened = await env.service.open({ path: '/reg-retry', name: '重试项目' })
|
||||||
|
const leadView = await env.service.enableSeat(opened.project.id, 'lead')
|
||||||
|
const leadSessionId = seatById(leadView, 'lead').sessionId
|
||||||
|
const agent = env.fake.sessions.get(leadSessionId)
|
||||||
|
const registered = []
|
||||||
|
let remainingFailures = 2
|
||||||
|
agent.ctx = {
|
||||||
|
tools: {
|
||||||
|
register(def) {
|
||||||
|
if (def.name === 'sansheng_task_report' && remainingFailures > 0) {
|
||||||
|
remainingFailures -= 1
|
||||||
|
throw new Error('模拟注册失败')
|
||||||
|
}
|
||||||
|
registered.push(def.name)
|
||||||
|
return () => {}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
const listeners = new Map()
|
||||||
|
const ctx = {
|
||||||
|
agents: { list: () => [...env.fake.sessions.values()], get: id => env.fake.sessions.get(id) },
|
||||||
|
on(event, fn) {
|
||||||
|
if (!listeners.has(event)) listeners.set(event, new Set())
|
||||||
|
listeners.get(event).add(fn)
|
||||||
|
return () => listeners.get(event)?.delete(fn)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
const teardown = installSeatTools(ctx, { store: env.store, service: env.service, provisioner: env.provisioner })
|
||||||
|
try {
|
||||||
|
assert.equal(registered.length, 4, '首轮 1 个注册失败,应只装 4 个')
|
||||||
|
// 再触发一次创建事件,缺失的工具应被重试补装
|
||||||
|
for (const fn of [...(listeners.get('agent/created') ?? [])]) fn({ agent })
|
||||||
|
assert.equal(registered.length, 5, '重试后应补齐到 5 个')
|
||||||
|
assert.ok(registered.includes('sansheng_task_report'))
|
||||||
|
} finally {
|
||||||
|
teardown()
|
||||||
|
}
|
||||||
|
})
|
||||||
Loading…
Reference in New Issue