Archived
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KeDBx2PHLavbURXB8LJJ7m
389 lines
16 KiB
TypeScript
389 lines
16 KiB
TypeScript
/**
|
|
* 工作台路由 —— 五要素是**同一份过程事实的五种投影**(编码规范 §3;语义出处 OS 2.1)。
|
|
*
|
|
* 「web 是纯呈现与输入面」:这里出的每一样都是服务端投影,前端零过程状态、刷新即重建(§9.2)。
|
|
*/
|
|
import type { Hono } from 'hono';
|
|
import type { ApiError, ChainNode, ChatMessage, Deliverable, FileDoc, TaskCard, ViewBlock } from '@contracts';
|
|
import {
|
|
ATTRIBUTION_SIDE_LABEL,
|
|
answerMessageRoute,
|
|
chatCardReplySchema,
|
|
listMessagesRoute,
|
|
markMessageReadRoute,
|
|
listTasksRoute,
|
|
replyChatCardRoute,
|
|
replyWorkOrderRoute,
|
|
sayRoute,
|
|
taskDetailRoute,
|
|
staffIdSchema,
|
|
taskIdSchema,
|
|
workOrderReplySchema,
|
|
} from '@contracts';
|
|
import { ReplyRejectedError } from '@modules/human-tool';
|
|
import type { Container } from '../container.ts';
|
|
import type { AppEnv } from '../http-env.ts';
|
|
|
|
export function registerDeskRoutes(app: Hono<AppEnv>, container: Container): void {
|
|
/** 当前登录者;缺会话即 401 */
|
|
async function me(account: string) {
|
|
const staff = await container.org.findByAccount(account);
|
|
return staff;
|
|
}
|
|
|
|
/** 任务卡 —— 一条 = 一个活动的一次运行;序位取自工作流的节点实例 */
|
|
async function toCard(task: Awaited<ReturnType<Container['task']['get']>>): Promise<TaskCard> {
|
|
let position = 1;
|
|
let total = 1;
|
|
let subject = task.title;
|
|
let workflowState: TaskCard['workflowState'] = 'running';
|
|
|
|
if (task.workflowId !== undefined) {
|
|
const workflow = await container.process.getWorkflow(task.workflowId).catch(() => undefined);
|
|
if (workflow !== undefined) {
|
|
subject = workflow.subject;
|
|
workflowState = workflow.state;
|
|
const pkg = await container.process.getPackage(workflow.packageId, workflow.packageVersion);
|
|
const activityNodes = (pkg?.nodes ?? []).filter((n) => n.kind === 'activity' || n.kind === 'approval');
|
|
total = Math.max(activityNodes.length, 1);
|
|
const index = activityNodes.findIndex((n) => n.id === task.nodeId);
|
|
position = index < 0 ? 1 : index + 1;
|
|
}
|
|
}
|
|
|
|
return {
|
|
id: task.id,
|
|
activity: task.title,
|
|
title: task.title,
|
|
runtime: task.runtime,
|
|
...(task.terminal === undefined ? {} : { terminal: task.terminal }),
|
|
position,
|
|
total,
|
|
workflowSubject: subject,
|
|
workflowState,
|
|
startedAt: task.startedAt,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 流程链 —— 人要看见自己在整条流程的哪一环,以及前后是谁。
|
|
* 别人负责的节点在链上只读呈现,不进任务清单(清单只装我负责的)。
|
|
*/
|
|
async function toChain(task: Awaited<ReturnType<Container['task']['get']>>): Promise<ChainNode[]> {
|
|
if (task.workflowId === undefined) return [];
|
|
const workflow = await container.process.getWorkflow(task.workflowId).catch(() => undefined);
|
|
if (workflow === undefined) return [];
|
|
const pkg = await container.process.getPackage(workflow.packageId, workflow.packageVersion);
|
|
|
|
/*
|
|
* 链的呈现顺序:**按流程列位排,同列按节点编号排** —— 不吃 `nodes` 数组的书写顺序。
|
|
*
|
|
* 并行分支(如 G2 分出的 A2 / A3)在图上本无先后,链却必须挑一个顺序。
|
|
* 挑「作者数组里怎么写」是最不稳的:换个人写包,链的读法就变了。
|
|
* 列位 `layout.col` 是流程的推进次序(拓扑的可视化),同列的并行支再按编号定 ——
|
|
* 于是链永远读作 A1 → A2 → A3 → A4,与人对活动编号的预期一致。
|
|
* `layout` 声明为「不影响语义」,这里也只拿它排**呈现**,不参与任何流转判断。
|
|
*/
|
|
const declared = (pkg?.nodes ?? []).filter((n) => n.kind === 'activity' || n.kind === 'approval');
|
|
const nodes = declared
|
|
.map((n, index) => ({ n, index }))
|
|
.sort(
|
|
(a, b) =>
|
|
(a.n.layout?.col ?? a.index) - (b.n.layout?.col ?? b.index) ||
|
|
(a.n.id < b.n.id ? -1 : a.n.id > b.n.id ? 1 : 0),
|
|
)
|
|
.map((x) => x.n);
|
|
|
|
/*
|
|
* 状态取**真实的节点实例**,不按下标推。
|
|
* 按下标推(「排在当前之前的就算做完」)在并行支上会说谎:人在 A3 时 A2 可能还在跑,
|
|
* 却被标成已完成。宁可把在跑的并行支报作待办(少报),也不能把没做完的说成做完了。
|
|
*/
|
|
const instances = await container.process.instancesOf(workflow.id).catch(() => []);
|
|
const finished = new Set(instances.filter((x) => x.terminal !== undefined).map((x) => x.nodeId));
|
|
|
|
return await Promise.all(
|
|
nodes.map(async (n) => {
|
|
const spec = n.kind === 'approval' ? n.approver : n.owner;
|
|
|
|
/*
|
|
* 报谁,要和**真正派单时的口径一致**(ADR-011:绑定先于策略)。
|
|
* 只按岗位报人的话,装了工作组的单会当面说谎:整条流实际都归起单人,
|
|
* 链上却写着各岗位的常驻人。所以这里也先看工作组绑定,再退回岗位解析。
|
|
*/
|
|
const bound = workflow.workGroup?.[spec.position];
|
|
const boundStaff =
|
|
bound === undefined
|
|
? undefined
|
|
: await container.org.getStaff(staffIdSchema.parse(bound)).catch(() => undefined);
|
|
|
|
// 岗位唯一解析(sole)即报人名;否则只报岗位 —— 不编造具体承接人
|
|
const holders =
|
|
boundStaff !== undefined ? [] : await container.org.staffOfPosition(spec.position).catch(() => []);
|
|
const who = boundStaff ?? (holders.length === 1 ? holders[0] : undefined);
|
|
return {
|
|
nodeId: n.id,
|
|
label: n.label,
|
|
kind: n.kind === 'approval' ? ('approval' as const) : ('activity' as const),
|
|
ownerName: who?.name ?? spec.position,
|
|
ownerRole: who?.position.name ?? spec.position,
|
|
state:
|
|
n.id === task.nodeId
|
|
? ('current' as const)
|
|
: finished.has(n.id)
|
|
? ('done' as const)
|
|
: ('todo' as const),
|
|
};
|
|
}),
|
|
);
|
|
}
|
|
|
|
app.get(listTasksRoute.path, async (c) => {
|
|
const staff = await me(c.get('account'));
|
|
if (staff === undefined) {
|
|
const body: ApiError = { code: 'unauthenticated', message: '会话无效' };
|
|
return c.json(body, 401);
|
|
}
|
|
// 任务要素永远只装「我负责的任务」—— 跨人卡进对方的消息要素,不占任务清单
|
|
const tasks = await container.task.listByOwner(staff.id);
|
|
return c.json({ tasks: await Promise.all(tasks.map(toCard)) });
|
|
});
|
|
|
|
app.get(taskDetailRoute.path, async (c) => {
|
|
const staff = await me(c.get('account'));
|
|
if (staff === undefined) {
|
|
const body: ApiError = { code: 'unauthenticated', message: '会话无效' };
|
|
return c.json(body, 401);
|
|
}
|
|
const taskId = taskIdSchema.parse(c.req.param('taskId'));
|
|
const task = await container.task.get(taskId);
|
|
|
|
const [workOrders, chat, lines, pushed] = await Promise.all([
|
|
// 全部工单:待处理要翻页办,已办结要回看定稿报告 —— 两摞同源
|
|
container.humanTool.allWorkOrders(taskId),
|
|
container.interaction.timeline(taskId),
|
|
container.memory.taskLog(taskId),
|
|
container.interaction.viewOf(taskId),
|
|
]);
|
|
const cards = await container.humanTool.chatCards(taskId);
|
|
const chain = await toChain(task);
|
|
|
|
/*
|
|
* 工作成果 = 一组**文件**,大部分是 HTML 汇报报告。
|
|
* 两处来源:
|
|
* ① 活动推的那一屏 —— 它就是这单当下的汇报报告(AM 07);
|
|
* ② 过程成果里声明的 `files` 块 —— 活动按需生成的目标输出(报价单 / 台账 / 档案)。
|
|
* 活动尚未产出文件时给空列表,界面落空态,不编造条目。
|
|
*/
|
|
/*
|
|
* 过程成果尚无来源:活动还不发布 deliverable(一个个活动开发时逐步补上)。
|
|
* 先声明出来并接进成果文件的装配 —— 活动一开始产出,文件列表就自动有了。
|
|
*/
|
|
const deliverables: Deliverable[] = [];
|
|
|
|
const results: Array<{ label: string; desc: string; at?: string; file: FileDoc }> = [];
|
|
if (pushed?.html !== undefined) {
|
|
results.push({
|
|
label: `${task.title} · 汇报报告`,
|
|
desc: 'HTML · 活动按当下局面组织的一屏',
|
|
file: { kind: 'html', name: `${task.activityId}-report.html`, html: pushed.html },
|
|
});
|
|
}
|
|
for (const deliverable of deliverables) {
|
|
for (const block of deliverable.blocks) {
|
|
if (block.t !== 'files') continue;
|
|
for (const item of block.items) {
|
|
results.push({
|
|
label: item.label,
|
|
desc: item.desc,
|
|
...(deliverable.at === undefined ? {} : { at: deliverable.at }),
|
|
file: item.file,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
// 对话流 = 时间线 + 对话卡族,按时间全序 —— 与任务记忆同源、不同筛选
|
|
const merged: ChatMessage[] = [...chat, ...cards].sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));
|
|
|
|
// 视图区:活动推的 HTML 优先(它是活动按局面组织的完整一屏);
|
|
// 尚无推送时给一份进度概览,不留空屏
|
|
const view: ViewBlock[] = [
|
|
{
|
|
t: 'kv',
|
|
title: '任务概览',
|
|
items: [
|
|
{ k: '活动', v: task.activityId },
|
|
{ k: '负责人', v: staff.name },
|
|
{ k: '状态', v: task.runtime },
|
|
{ k: '已用步数', v: `${task.used.steps} / ${task.caps.steps}` },
|
|
],
|
|
},
|
|
];
|
|
|
|
return c.json({
|
|
card: await toCard(task),
|
|
goal: task.title,
|
|
owner: { name: staff.name, role: staff.position.name },
|
|
chain,
|
|
budget: {
|
|
steps: `${task.used.steps}/${task.caps.steps}`,
|
|
tokens: `${task.used.tokens}/${task.caps.tokens}`,
|
|
activeMinutes: `${Math.round(task.used.activeMs / 60_000)}/${task.caps.activeMinutes}`,
|
|
humanCalls: `${task.used.humanCalls}/${task.caps.humanCalls}`,
|
|
},
|
|
stages: [],
|
|
deliverables,
|
|
results,
|
|
workOrders,
|
|
chat: merged,
|
|
view: pushed?.blocks !== undefined ? [...pushed.blocks] : view,
|
|
...(pushed?.html === undefined ? {} : { viewHtml: pushed.html }),
|
|
log: lines.map((l) => ({
|
|
id: l.id,
|
|
at: l.at,
|
|
side: l.side,
|
|
sideLabel: ATTRIBUTION_SIDE_LABEL[l.side],
|
|
title: l.title,
|
|
...(l.summary === undefined ? {} : { summary: l.summary }),
|
|
})),
|
|
});
|
|
});
|
|
|
|
/** 回传:与后端回传校验**同 schema** —— 前端提交校验用的也是它 */
|
|
app.post(replyWorkOrderRoute.path, async (c) => {
|
|
const staff = await me(c.get('account'));
|
|
if (staff === undefined) {
|
|
const body: ApiError = { code: 'unauthenticated', message: '会话无效' };
|
|
return c.json(body, 401);
|
|
}
|
|
const parsed = workOrderReplySchema.safeParse((await c.req.json())['reply']);
|
|
if (!parsed.success) {
|
|
const body: ApiError = { code: 'validation-failed', message: '回传不合协议', detail: parsed.error.issues };
|
|
return c.json(body, 400);
|
|
}
|
|
try {
|
|
const outcome = await container.humanTool.replyWorkOrder(parsed.data, staff.id);
|
|
return c.json({ ok: true, producesCompletion: outcome.producesCompletion });
|
|
} catch (error) {
|
|
if (error instanceof ReplyRejectedError) {
|
|
// 驳回必附意见 / 必填未回填 / 已答不得再答 —— 三规矩的回传面
|
|
const body: ApiError = { code: 'validation-failed', message: error.message, detail: error.violations };
|
|
return c.json(body, 400);
|
|
}
|
|
throw error;
|
|
}
|
|
});
|
|
|
|
/**
|
|
* 对话卡回传(决策 / 补全 / 评价)。
|
|
* 与工单回传同一条规矩:校验用**同 schema**,拒收由 human-tool 判定并给出违规明细。
|
|
*/
|
|
app.post(replyChatCardRoute.path, async (c) => {
|
|
const staff = await me(c.get('account'));
|
|
if (staff === undefined) {
|
|
const body: ApiError = { code: 'unauthenticated', message: '会话无效' };
|
|
return c.json(body, 401);
|
|
}
|
|
const parsed = chatCardReplySchema.safeParse((await c.req.json())['reply']);
|
|
if (!parsed.success) {
|
|
const body: ApiError = { code: 'validation-failed', message: '回传不合协议', detail: parsed.error.issues };
|
|
return c.json(body, 400);
|
|
}
|
|
try {
|
|
await container.humanTool.replyChatCard(parsed.data, staff.id);
|
|
return c.json({ ok: true });
|
|
} catch (error) {
|
|
if (error instanceof ReplyRejectedError) {
|
|
// 补全两条路必走其一 / 已答不得再答 —— 三规矩的回传面
|
|
const body: ApiError = { code: 'validation-failed', message: error.message, detail: error.violations };
|
|
return c.json(body, 400);
|
|
}
|
|
throw error;
|
|
}
|
|
});
|
|
|
|
/** 自由输入 —— 人事件的第二形态:写入任务记忆,loop 作为观察;不驱动 flow 步 */
|
|
app.post(sayRoute.path, async (c) => {
|
|
const staff = await me(c.get('account'));
|
|
if (staff === undefined) {
|
|
const body: ApiError = { code: 'unauthenticated', message: '会话无效' };
|
|
return c.json(body, 401);
|
|
}
|
|
const taskId = taskIdSchema.parse(c.req.param('taskId'));
|
|
const parsed = sayRoute.body.safeParse(await c.req.json());
|
|
if (!parsed.success) {
|
|
const body: ApiError = { code: 'validation-failed', message: '入参不合法' };
|
|
return c.json(body, 400);
|
|
}
|
|
return c.json(await container.interaction.say(taskId, staff.id, parsed.data.text));
|
|
});
|
|
|
|
app.get(listMessagesRoute.path, async (c) => {
|
|
const staff = await me(c.get('account'));
|
|
if (staff === undefined) {
|
|
const body: ApiError = { code: 'unauthenticated', message: '会话无效' };
|
|
return c.json(body, 401);
|
|
}
|
|
const messages = await container.message.inbox(staff.id);
|
|
return c.json({
|
|
messages: messages.map((m) => ({
|
|
id: m.id,
|
|
kind: m.kind,
|
|
title: m.title,
|
|
body: m.body,
|
|
at: m.at,
|
|
read: m.readAt !== undefined,
|
|
// 跨任务征答卡随消息一并出:就地作答,不必跳进别人的任务
|
|
...(m.card === undefined
|
|
? {}
|
|
: {
|
|
card: {
|
|
cardId: m.card.cardId,
|
|
sourceTaskId: m.card.sourceTaskId,
|
|
fields: (m.card.payload['fields'] as unknown[] | undefined) ?? [],
|
|
ask: String(m.card.payload['ask'] ?? ''),
|
|
answered: m.card.answeredAt !== undefined,
|
|
...(m.card.rejectedReason === undefined ? {} : { rejectedReason: m.card.rejectedReason }),
|
|
...(m.card.supersededBy === undefined ? {} : { supersededBy: m.card.supersededBy }),
|
|
},
|
|
}),
|
|
})),
|
|
});
|
|
});
|
|
|
|
app.post(markMessageReadRoute.path, async (c) => {
|
|
const staff = await me(c.get('account'));
|
|
if (staff === undefined) {
|
|
const body: ApiError = { code: 'unauthenticated', message: '会话无效' };
|
|
return c.json(body, 401);
|
|
}
|
|
await container.message.markRead(c.req.param('messageId'));
|
|
return c.json({ ok: true });
|
|
});
|
|
|
|
/**
|
|
* 跨任务征答的**就地作答**(OS 2.1)。
|
|
* 「作答权限只及卡面与决策包,**不开放任务对话流**」——所以这里只收卡面回传,
|
|
* 由 message 经统一入口写回来源任务;调用与回传全程在任务侧留痕。
|
|
*/
|
|
app.post(answerMessageRoute.path, async (c) => {
|
|
const staff = await me(c.get('account'));
|
|
if (staff === undefined) {
|
|
const body: ApiError = { code: 'unauthenticated', message: '会话无效' };
|
|
return c.json(body, 401);
|
|
}
|
|
const parsed = answerMessageRoute.body.safeParse(await c.req.json());
|
|
if (!parsed.success) {
|
|
const body: ApiError = { code: 'validation-failed', message: '回传不合协议' };
|
|
return c.json(body, 400);
|
|
}
|
|
const answered = await container.message.answer(c.req.param('messageId'), staff.id, parsed.data.answer);
|
|
// 跨人卡一答,来源任务就可能续跑 —— 让那边的浏览器重取投影
|
|
if (answered.card !== undefined) {
|
|
container.broadcaster.publish({ kind: 'task', id: answered.card.sourceTaskId, reason: 'elicitation-answer' });
|
|
}
|
|
return c.json({ ok: true });
|
|
});
|
|
}
|