182 lines
7.2 KiB
TypeScript
182 lines
7.2 KiB
TypeScript
import { useEffect, useMemo, useRef, useState } from 'react';
|
|
import type { DigitalStaff, MetricNode } from '../data/sqlite';
|
|
import type { I18n } from '../i18n/locales';
|
|
import { buildAskAnswer } from '../lib/ibpAsk';
|
|
import type { AskAnswer, IntentId } from '../lib/ibpAsk';
|
|
import { buildConsultScript } from '../lib/teams';
|
|
import type { ConsultTurn, ExpertTeam } from '../lib/teams';
|
|
|
|
/**
|
|
* 底部对话区的会话状态机:问候语 → 单轮问答(思考步骤逐条揭示)→ 专家团会诊播报。
|
|
*
|
|
* 状态放在 hook 里、由 MetricWorkspace 持有,而不是放在 AgentDock 组件内部:
|
|
* 本体舞台会替换掉整块内容区,对话区组件随之卸载;状态上提后
|
|
* 「从回答卡点进业务本体总览」再退回来,会话历史与进行中的推演都不会丢。
|
|
*/
|
|
|
|
export interface Msg {
|
|
id: number;
|
|
role: 'user' | 'ai';
|
|
text: string;
|
|
staff?: string;
|
|
time: string;
|
|
/** 专家团会诊:发言者名 / 角色标签 / 发言类型(系统播报 / 成员 / 牵头汇总) */
|
|
name?: string;
|
|
tag?: string;
|
|
kind?: 'system' | 'member' | 'lead';
|
|
/** 专家团结构化发言(成员卡 / 牵头结论卡的数据源) */
|
|
turn?: ConsultTurn;
|
|
/** 单轮问答:规范回答卡(结论 / 关键数字 / 明细 / 依据 / 行动 / 来源) */
|
|
answer?: AskAnswer;
|
|
/** 该回答的思考过程耗时(秒):步骤揭示完写回,卡头展示 */
|
|
elapsed?: number;
|
|
}
|
|
|
|
/** 思考中的回答:steps 按 revealed 逐条揭示,全部揭示后才落卡 */
|
|
export interface PendingAsk {
|
|
answer: AskAnswer;
|
|
staff?: string;
|
|
revealed: number;
|
|
/** performance.now() 起点,用于卡头「耗时 x.xs」 */
|
|
started: number;
|
|
}
|
|
|
|
export interface AgentChat {
|
|
msgs: Msg[];
|
|
/** 揭示中的问答:对话区用它渲染逐条出现的思考轨 */
|
|
pending: PendingAsk | null;
|
|
/** 会诊播报间隔的「分析中」气泡 */
|
|
thinking: boolean;
|
|
/** 输入区是否该锁住:会诊播报中或思考轨揭示中都算忙 */
|
|
busy: boolean;
|
|
draft: string;
|
|
setDraft: (v: string) => void;
|
|
ask: (raw: string) => void;
|
|
/** 清空:回到问候语,并掐掉所有在飞的定时器 */
|
|
reset: () => void;
|
|
}
|
|
|
|
const clock = () => {
|
|
const d = new Date();
|
|
const p = (n: number) => String(n).padStart(2, '0');
|
|
return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
|
};
|
|
|
|
/** 意图 → 在岗数字员工:回答卡头部标注归属,保留「数字员工协同」的设定 */
|
|
const DISPATCH: Record<IntentId, string> = {
|
|
delay: 'ORDR', bottleneck: 'SCHED', po: 'ALERT', material: 'DATA', gap: 'DATA', ledger: 'REPORT', help: 'METRIX',
|
|
};
|
|
|
|
interface Input {
|
|
staff: DigitalStaff[];
|
|
byCode: Map<string, MetricNode>;
|
|
/** 会诊聚焦的指标:触发时快照,避免左侧选中变化导致会诊重跑 */
|
|
selected?: MetricNode;
|
|
team: ExpertTeam | null;
|
|
t: I18n;
|
|
}
|
|
|
|
export function useAgentChat({ staff, byCode, selected, team, t }: Input): AgentChat {
|
|
const [draft, setDraft] = useState('');
|
|
const [thinking, setThinking] = useState(false);
|
|
const [msgs, setMsgs] = useState<Msg[]>([]);
|
|
const [pending, setPending] = useState<PendingAsk | null>(null);
|
|
const seq = useRef(0);
|
|
const staffRef = useRef(staff); staffRef.current = staff;
|
|
const byCodeRef = useRef(byCode); byCodeRef.current = byCode;
|
|
const selectedRef = useRef(selected); selectedRef.current = selected;
|
|
const timersRef = useRef<number[]>([]);
|
|
const clearTimers = () => { timersRef.current.forEach(id => window.clearTimeout(id)); timersRef.current = []; };
|
|
|
|
const onDuty = useMemo(() => staff.filter(s => s.status !== 'offline'), [staff]);
|
|
const busy = thinking || !!pending;
|
|
|
|
// 问候语随文案变化刷新(不劫持用户正在输入的草稿)
|
|
useEffect(() => {
|
|
if (team) return; // 专家团激活时对话区交给会诊序列,不覆盖
|
|
clearTimers();
|
|
setPending(null);
|
|
seq.current = 0;
|
|
setMsgs([{ id: 0, role: 'ai', text: t.agent.greeting, staff: t.agent.subtitle, time: clock() }]);
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [t.agent.greeting, t.agent.subtitle, team]);
|
|
|
|
// 专家团会诊:按脚本依次播报(就位播报 → 各专家轮流发言 → 牵头汇总结论)
|
|
useEffect(() => {
|
|
clearTimers();
|
|
if (!team) return;
|
|
setPending(null);
|
|
const staffByCode = new Map(staffRef.current.map(x => [x.code, x]));
|
|
const script = buildConsultScript(team, staffByCode, byCodeRef.current, selectedRef.current);
|
|
seq.current = 0;
|
|
setThinking(false);
|
|
setMsgs([]);
|
|
let delay = 160;
|
|
script.forEach((turn, i) => {
|
|
if (i > 0) timersRef.current.push(window.setTimeout(() => setThinking(true), Math.max(0, delay - 420)));
|
|
timersRef.current.push(window.setTimeout(() => {
|
|
// id 必须在 updater 外定值:updater 需保持纯函数,批处理时否则多条消息读到同一 seq 撞 key
|
|
const id = ++seq.current;
|
|
const time = clock();
|
|
setThinking(false);
|
|
setMsgs(prev => [...prev, {
|
|
id, role: 'ai', text: turn.text ?? '',
|
|
name: turn.name, tag: turn.tag, kind: turn.kind, turn, time,
|
|
}]);
|
|
}, delay));
|
|
delay += turn.kind === 'lead' ? 1500 : turn.kind === 'system' ? 900 : 1150;
|
|
});
|
|
return clearTimers;
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [team]);
|
|
|
|
/* 揭示节奏:首步 420ms 起步,其后每步 520–700ms 轻微抖动,步骤走完停 700ms 再落卡。
|
|
刻意慢于「瞬间甩结果」,让取数—建链路—跑规则—排序的推演过程可见;
|
|
总耗时回写进卡头,用户可复核它确实跑了这几步。 */
|
|
useEffect(() => {
|
|
if (!pending) return;
|
|
const atEnd = pending.revealed >= pending.answer.steps.length;
|
|
const delay = atEnd ? 700 : pending.revealed === 0 ? 420 : 520 + Math.round(Math.random() * 180);
|
|
const id = window.setTimeout(() => {
|
|
if (atEnd) {
|
|
const elapsed = (performance.now() - pending.started) / 1000;
|
|
setMsgs(prev => [...prev, {
|
|
id: ++seq.current, role: 'ai', text: pending.answer.conclusion,
|
|
answer: pending.answer, elapsed, staff: pending.staff, time: clock(),
|
|
}]);
|
|
setPending(null);
|
|
} else {
|
|
setPending(p => (p ? { ...p, revealed: p.revealed + 1 } : p));
|
|
}
|
|
}, delay);
|
|
return () => window.clearTimeout(id);
|
|
}, [pending]);
|
|
|
|
// 提问 → 履约风险问答引擎 → 思考步骤逐条揭示 → 规范回答卡落位
|
|
const ask = (raw: string) => {
|
|
const text = raw.trim();
|
|
if (!text || busy) return;
|
|
const { intent, answer } = buildAskAnswer(text);
|
|
const who = onDuty.find(s => s.code === DISPATCH[intent]) ?? onDuty[0];
|
|
setMsgs(prev => [...prev, { id: ++seq.current, role: 'user', text, time: clock() }]);
|
|
setDraft('');
|
|
setPending({
|
|
answer,
|
|
staff: who ? `${t.agent.dispatched}${who.name_zh}` : undefined,
|
|
revealed: 0,
|
|
started: performance.now(),
|
|
});
|
|
};
|
|
|
|
const reset = () => {
|
|
clearTimers();
|
|
setPending(null);
|
|
setThinking(false);
|
|
setDraft('');
|
|
seq.current = 0;
|
|
setMsgs([{ id: 0, role: 'ai', text: t.agent.greeting, staff: t.agent.subtitle, time: clock() }]);
|
|
};
|
|
|
|
return { msgs, pending, thinking, busy, draft, setDraft, ask, reset };
|
|
}
|